Reputation: 8335
When I declare a new object type :
var MyType = function(constructorArg) {
this.whatever = constructorArg;
};
var myTypeInstance = new MyType('hehe');
In that case, this
refers to the function assigned to MyType
.
Now let's add a simple accessor for the property whatever
(without using the prototype) :
var MyType = function(constructorArg) {
this.whatever = constructorArg;
this.getWhatever = function() {
// Here this should logically point to the function assigned
// to this.whatever instead of the current instance of MyType.
return this.whatever;
};
};
This works right ?
But why isn't this
, inside the body of the function assigned to the property whatever
, not pointing to that function itself ?
Thanks for your help !
EDIT
: I'll modify my example :
var MyType = function(arg) {
this.property = arg;
this.MySubType = function(subTypeArg) {
this.subTypeProperty = subTypeArg;
// What is "this" refereing to here ?
// To the instance of MyType, or to the instance of MySubType ?
// I know it would not make sense to do something like this in real world
// but i'm trying to have a clearer understanding of the way "this" is set.
};
}
EDIT
: As said in the comments :
When using
myTypeInstance.MySubType('hehe');
then this refers to myTypeInstance.
When using
var mySubTypeInstance = new myTypeInstance.MySubType('hehe');
then this refers to mySubTypeInstance
If i understood well.
Upvotes: 0
Views: 64
Reputation: 816780
Regarding your edit, it is like it always is: It depends on how you call this.MySubType
.
If you call it as this.MySubType()
, i.e. as object method, then this
(inside the function) would refer to this
(outside the function), which is an instance of MyType
.
If you call it as new this.MySubType()
then it refers to a new instance of MySubType
.
If you call it as this.MySubType.call(foo)
, this
refers to foo
.
Have a look at the MDN documentation, section "Function context".
Upvotes: 1
Reputation: 692
I don't think this gets a new value assigned to it inside an anonymous function. You might want to look this page.
- The inner function can be accessed only from statements in the outer function.
- The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
My guess would be that this must be accessable from inside the inner function and as such will not be overwritten.
Edit: I did not see the comments while typing, Felix Kling explains it much better in his comment.
Upvotes: 0