JavaScript寄生继承中"this"指的是什么?

Bre*_*mpa 7 javascript

在JavaScript中使用原型继承创建应用程序多年后,我开始探索使用寄生继承.尽管在创建对象层次结构时可能会在内存中创建多个方法副本,但至少对我来说存在主要的缺陷,我发现它的简单性以及"新"变得不必要的事实让我产生了共鸣.但是,我坚持用"这个"发生的事情.我在网上看到的大多数例子都只是在表面上展示如何实现寄生继承,如下所示:

   function foo() {
       return {
          method1 : function() {...}
       }
   }

   function bar() {
       var that = foo();
       that.method2 = function() {
           //is "this" pointing to bar()?
       }
       return that;
   }
Run Code Online (Sandbox Code Playgroud)

正如我在bar()对象的注释中所说的那样,"this"是指bar()还是这个降级为method2的范围?

谢谢!

nra*_*itz 3

快速测试表明this正确引用了 返回的对象bar

function foo() {
    return {
        method1 : function() { return "spam" }
    }
}

function bar() {
    var that = foo();
    that.method2 = function() {
        return this.method1();
    }
    return that;
}

var b = bar();
b.method2(); // "spam"
Run Code Online (Sandbox Code Playgroud)