【问题标题】:Nested function invoked as method in JavaScript在 JavaScript 中作为方法调用的嵌套函数
【发布时间】:2017-09-18 07:43:26
【问题描述】:

我正在阅读 JS Definitive Guide 6th edition,我遇到了以下几行:

与变量不同,this 关键字没有作用域,嵌套函数没有 继承调用者的 this 值。如果嵌套函数作为方法调用,它的 这个值是它被调用的对象。如果嵌套函数作为函数调用 那么它的 this 值将是全局对象(非严格模式)或未定义(严格 模式)。

我的理解是函数在严格模式下返回全局或未定义作为 this 的值。同样在 methods 中, this 指的是调用该方法的对象。 从函数或方法调用的嵌套函数也有 this 引用全局或严格模式下未定义的对象。

举个例子:

var o = {                            // An object o.
    m: function() {                  // Method m of the object.
        var self = this;             // Save the this value in a variable.
        console.log(this === o);     // Prints "true": this is the object o.
        f();                         // Now call the helper function f().

        function f() {               // A nested function f
            console.log(this === o); // "false": this is global or undefined
            console.log(self === o); // "true": self is the outer this value.
        }
    }
};
o.m(); // Invoke the method m on the object o.

但我不明白的是:如果将嵌套函数作为方法调用,它的 this 值就是它被调用的对象

你能举个例子,嵌套函数作为方法被调用并且它的 this 值引用了它被调用的对象吗?

【问题讨论】:

  • 只需执行o.method = f; 即可调用它为o.method()

标签: javascript function methods nested this


【解决方案1】:

如果我理解正确,

function f() {               // A nested function f
            console.log(this === o); // "false": this is global or undefined
            console.log(self === o); // "true": self is the outer this value.
        }

在上面的代码中,this 指的是window 对象。如果你想让this 指向o 对象本身,那么你应该使用apply, bind, or call

点赞f.call(this)

【讨论】:

  • 替换'var that = this'之类代码的好方法
【解决方案2】:

如果例如m 方法返回另一个具有n 方法的对象,您可以看到该方法中this 的上下文是嵌套对象而不是父对象,因为this.a 未定义。

var o = {
  a: 1,
  m: function() {
    console.log('Parent: ' + this.a)
    
    return {
    	b: 2,
    	n: function() {
      	console.log('Nested: ' + this.a);
        console.log('Nested: ' + this.b);
      }
    }
  }
};

o.m().n()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2016-02-09
    • 2015-03-18
    相关资源
    最近更新 更多