this指向?

this is set according to how the method is called, and not according to how the method is written. So for obj.method(), this will be set to obj inside of method(). For obj.method.call(x), this inside of method() will be set to x. It is determined by how it’s called. What that also means is that if you pass it as a callback to e.g. onclick, this will be set to the global window object rather than what you expect.

参考1:https://stackoverflow.com/questions/13224620/the-this-keyword-returns-the-window-object-within-an-objects-prototype-in-jav

参考2:https://segmentfault.com/a/1190000008400124

JavaScript 函数中的 this 指向并不是在函数定义的时候确定的,而是在调用的时候确定的。换句话说,函数的调用方式决定了 this 指向

Game = function() {

this.name = ‘Lee’;

}

Game.prototype.pay = function() {

console.log(this);

}

// 在不同的调用方法下,this指向?哪种情况下this会指向window?

var game = new Game();

var pay = new Game().pay; // pay就是Game的pay方法,但是pay()调用时,this指向了全局

game.pay(); // this指向Game

pay(); // this指向window

发表评论

电子邮件地址不会被公开。 必填项已用*标注