javascript原型和关闭中的"this"访问

Dav*_*eau 5 javascript closures object

我是js的初学者,我对以下代码感到困惑:

Foo = function(arg) {
    this.arg = arg;
};

Foo.prototype = {
    init: function () {
        var f = function () {
            alert("current arg: " + this.arg); // am expecting "bar", got undefined
        }
        f();
    }
};

var yo = Foo("bar");
yo.init();
Run Code Online (Sandbox Code Playgroud)

我被期望获得"当前的arg:bar",但得到了"当前的arg:undefined".我注意到,首先将this.arg复制到"普通"变量中,并在闭包中引用此变量:

Foo.prototype = {
    init: function () {
        var yo = this.arg;
        var f = function () {
            alert("current arg: " + yo);            }
        f();
    }
};
Run Code Online (Sandbox Code Playgroud)

我做错了什么,得到了错误的期望,还是属于js WTF之一?

bob*_*obo 3

这取决于函数的调用方式。

如果使用关键字调用new,则this引用正在构造的对象(将在函数末尾隐式返回)。

如果作为普通函数调用,this则引用全局window对象。

例子:

// Constructor for Foo,
// (invoke with keyword new!)
function Foo()
{
  this.name = "Foo" ;
}

myFoo = new Foo() ;
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ; // window.name will be empty

// now if we invoke Foo() WITHOUT keyword NEW
// then all references to `this` inside the
// function Foo will be to the
// __global window object__, i.e. the global window
// object will get clobbered with new properties it shouldn't
// have! (.name!)

Foo() ;  // incorrect invokation style!
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ;
Run Code Online (Sandbox Code Playgroud)

JavaScript 本身没有“构造函数”,JavaScript 知道你function实际上是“构造函数”的唯一方法是调用风格(即new每次调用它时都使用关键字)