简体   繁体   English

为什么此javascript单例方法有效

[英]Why this javascript singleton method works

function foo() {
    if (arguments.callee.self)
        return arguments.callee.self;
    arguments.callee.self = this;
    //do sth
}

I understand when it's called like this: 我知道何时这样调用:

var a = foo();

When foo gets executed, arguments.callee is foo itself. 当foo被执行时,arguments.callee就是foo本身。 So it passes this to the undefined variable self. 因此它将其传递给未定义的变量self。 Next time when another function calls foo, it returns this. 下次当另一个函数调用foo时,它将返回此值。 Clearly this will work. 显然,这将起作用。

Things seems to get tricker when it's called like this: 像这样被调用时,事情似乎变得更加棘手:

var b = new foo();

What I think is that js engine creates another instance of foo and execute its code. 我认为js引擎会创建foo的另一个实例并执行其代码。 But it seems that it passes back the this reference as self is already defined just like the same instance of foo. 但是似乎它回传了此引用,因为self已被定义,就像foo的相同实例一样。 Then what "new" actually does here? 那么,实际上什么是“新”呢?

new calls the function as a constructor. new将该函数作为构造函数调用。 If the target function explicitly returns an object, then that object will returned instead of the just created one. 如果目标函数显式返回一个对象,则将返回该对象,而不是刚刚创建的对象。

Since you are running this code under non-strict mode, the function explicitly returns the global object after first call, so it won't return the newly created object with new foo() 由于您是在非严格模式下运行此代码,因此该函数在首次调用后会显式返回全局对象,因此它将不会使用new foo()返回新创建的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM