Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第56题(2019-10-12):对作用域上下文和this的理解,看下列代码: #58

Open
qappleh opened this issue Oct 12, 2019 · 3 comments
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 12, 2019

var User = {
  count: 1,
  getCount: function() {
    return this.count;
  }
};
console.log(User.getCount());  // what?
var func = User.getCount;
console.log(func());  // what?  

问两处console输出什么?为什么?

@acgta5
Copy link

acgta5 commented Oct 12, 2019

1
undefined
第一次输出 this指向的是User , User.count为1 所以输出为1
第二次输出 将User.getCount的地址给了func,func调用 , this就指向了func,但func并没有赋值,所以输出undefined

@ghost
Copy link

ghost commented Oct 12, 2019

1 // this指向User
undefined // this指向window

@qappleh
Copy link
Owner Author

qappleh commented Oct 14, 2019

答案是1和undefined。

func是在winodw的上下文中被执行的,所以会访问不到count属性。

继续追问,那么如何确保Uesr总是能访问到func的上下文,即正确返回1。正确的方法是使用Function.prototype.bind。兼容各个浏览器完整代码如下:


Function.prototype.bind = Function.prototype.bind || function(context){
  var self = this;
  return function(){
    return self.apply(context, arguments);
  };
}
var func = User.getCount.bind(User);
console.log(func());  

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants