【问题标题】:Why can't prototype functions resolve 'this' in some cases?为什么原型函数在某些情况下不能解决“这个”?
【发布时间】:2016-12-03 00:22:07
【问题描述】:

这是一个例子

function banana() {
    this.size = 5;

    this.say_size = function() {
        console.log(this.size);
    }.bind(this);
}

banana.prototype.say_size2 = function() {
    console.log(this.size);
}

var b = new banana();

b.say_size();
b.say_size2();        //TLDR: why does this line work without binding?

setTimeout(b.say_size, 100);
setTimeout(b.say_size2, 200);

所以,在我直接调用 b.say_size 或 b.say_size2 的情况下,'this' 指的是香蕉对象,我得到 '5' 作为两者的输出。

如果函数被计时器或事件调用,'this' 设置为 window,除非被调用的函数绑定到对象。

我不明白 say_size2 在原型函数没有绑定到任何东西的情况下直接调用时如何获得正确的“this”?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    当您在对象上调用方法时,方法内的(b.say_size()b.say_size2())上下文指向该对象(this === b)。

    setTimeout 接受一个函数作为第一个参数,该函数在全局上下文 (this === window) 中执行。

    为简单起见,尝试将函数分配给变量并调用它:

    function banana() {
        this.size = 5;
    
        this.say_size = function() {
            console.log(this.size);
        //}.bind(this); Let's not bind yet
        }
    }
    
    banana.prototype.say_size2 = function() {
        console.log(this.size);
    }
    
    var b = new banana();
    
    b.say_size(); // 5 even without binding, instance method
    b.say_size2(); // 5, instance method from prototype chain
    
    var foo = b.say_size2;
    foo(); // undefined
    var bar = b.say_size;
    bar(); // undefined
    
    bar = b.say_size.bind(b);
    bar(); // 5

    在这两种情况下,这些函数都在全局上下文中执行,但是,由于 b.say_size 被显式绑定到不同的对象,JavaScript 引擎不会强制 thiswindow

    进一步阅读

    Forcing the context

    How does "this" keyword work within a function?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多