开发者社区 问答 正文

对作用域上下文和 this 的理解,看下列代码:

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

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

展开
收起
kun坤 2019-11-28 15:03:54 536 分享 版权
1 条回答
写回答
取消 提交回答
  • 答案: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());
    
    
    2019-11-28 15:04:04
    赞同 展开评论
问答地址: