We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
var User = { count: 1, getCount: function() { return this.count; } }; console.log(User.getCount()); // what? var func = User.getCount; console.log(func()); // what?
问两处console输出什么?为什么?
The text was updated successfully, but these errors were encountered:
1 undefined 第一次输出 this指向的是User , User.count为1 所以输出为1 第二次输出 将User.getCount的地址给了func,func调用 , this就指向了func,但func并没有赋值,所以输出undefined
Sorry, something went wrong.
1 // this指向User undefined // this指向window
答案是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());
No branches or pull requests
问两处console输出什么?为什么?
The text was updated successfully, but these errors were encountered: