javascript原型和“this”在闭合的访问 [英] javascript prototype and "this" access in closure

查看:158
本文介绍了javascript原型和“this”在闭合的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a beginner in js, and am puzzled by the following code:

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();



我希望得到current arg:bar,但得到current arg:undefined。我注意到,通过将this.arg复制到一个正常变量,并引用闭包中的这个变量工作:

I was expected to get "current arg: bar", but got "current arg: undefined". I noticed that by copying this.arg into a "normal" variable first, and refering this variable in the closure works:

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

我做错了事,错误的期望,还是落入js WTF之一?

Am I doing something wrong, got wrong expectations, or does it fall into one of the js WTF ?

推荐答案

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

It depends on how the function was invoked.

调用的关键字 new 然后这个引用被构造的对象(将隐式地返回函数的结尾)

If invoked with keyword new then this refers to the object being constructed (which will be implicitly returned at the end of the function).

如果作为普通函数调用, this 指全局 / code> object。

If invoked as a normal function, this refers to the global window object.

示例:

// 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 ) ;

JavaScript没有构造函数本身,唯一的方式是JavaScript知道你的 function 实际上是一个构造函数是调用样式(即每当调用它时使用关键字 new

JavaScript doesn't have "constructors" per se, the only way JavaScript knows that your function is actually a "constructor" is invokation style (namely you using keyword new whenever you invoke it)

这篇关于javascript原型和“this”在闭合的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆