So I have recently been learning about objects and methods in JavaScript and wrote this little example to help me understand things like "this" and methods a bit more.
objectTest = function() {
this.test = 1;
this.test2 = 2;
};
thisThing = new objectTest
thisThing.test3 = [1,2,3];
objectTest.prototype.whatIsThis = function(){
console.log(this.test);
};
thisThing.whatIsThis();
The output of the above code is 1
which makes sense because it refers to the this.test
, which i defined in the object.
Now what if i wrote objectTest
like this:
objectTest = function() {
var test = 1;
var test2 = 2;
};
If i console.log(this);
in my whatIsThis
Method i will simply get:
Object { test3=[3], whatIsThis=function()}
I am curious is there anyway for me to access the value of test and test2 without writing something like:
objectTest = function() {
var test = 1;
var test2 = 2;
return "test is" + test + "and test2 is" + test2;
};
Also if this is possible what would be a practical example of needing to do something like this?