Sarfraz
Sarfraz

Reputation: 382806

Cant understand what this refers to

Can anybody elaborate below in innerF, what does this refer to? User or innerF?

function User(){
  this.id = 1;
};

User.prototype.sayHi = function(){
    var innerF = function(){
        this.id = 2; // "this" refers to User or innerF ?
    };

    return innerF;
};

Also does the new keyword or anonymous function has to do with changing reference of this keyword?

What if I call it all like this:

var u = User;
var f = u.sayHi();
f();

Or

var u = new User;
var f = u.sayHi();
f();

Thanks

Upvotes: 3

Views: 161

Answers (3)

xdazz
xdazz

Reputation: 160883

var u = User;
var f = u.sayHi();
f();

The code above will throw error. User is a function, not a User object, so it doesn't have the method sayHi, so you will get error of below.

Uncaught TypeError: Object function User(){
  this.id = 1;
} has no method 'sayHi'

var u = new User;
var f = u.sayHi();
f();

The code above will not throw error, and u is an object of User, (how new worksfrom mdn), and it's method sayHi return a function, and you execute the function by f();, so the this inside of the function is refer the current context when the function be called. So if your code is in global scope, the this is referring the window object.

And you could set the context by f.call(u);, then the this is referring the object u, and you changed the User object u's id to 2.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755141

What the this local refers to inside of innerF will depend on how the function is eventually invoked. It can be invoked in a variety of ways that will change the meaning of this. For example

var u = new User();
var innerF = u.sayHi();
innerF();              // 'this' is window
innerF.call(u);        // 'this' is 'u'
innerF.call("hello");  // 'this' is "hello"

Based on your code though it appears that you want this to refer to the instance of User on which sayHi was invoked. If so then you need to store this in a local and refer to that local within innerF.

User.prototype.sayHi = function(){
    var self = this;
    var innerF = function(){
        self.id = 2; 
    };

    return innerF;
};

Note though that this inside sayHi isn't guaranteed to point to User instance either. In general it will the same tricks can be done to sayHi that were done to innerF. For example

var sayHi = u.sayHi;
sayHi();   // 'this' is window

Upvotes: 6

James M
James M

Reputation: 16718

You're not calling the function in that code, so it doesn't refer to anything yet.

The value of this is determined when you call the function, not define it (unless you use something like bind).

Upvotes: 2

Related Questions