我正在尝试解决underscore.js代码,但我在一开始就遇到了问题。这段代码被描述为“创建对下面使用的下划线对象的安全引用”。
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};我还是不明白。这是一个简单的函数还是构造函数?乍一看,它有:
this._wrapped = obj;所以它是构造函数,但它有两个返回的‘if’,那么当if的值为false时,它是构造函数吗?当其中一个if值为true时,它是构造函数吗?
还有其他问题:
if (!(this instanceof _)) return new _(obj);这里的'this‘是什么?为什么这证明了安全性。如果If get true是其自身创建对象呢?这是不是类似于递归?
发布于 2013-04-16 02:41:39
在JavaScript中,函数被用作构造函数。在使用new运算符时,任何函数都可以用作构造函数。以一个简单的sum函数为例:
function sum(a, b) {
return a + b;
}
var x = new sum(10, 2);
console.log(x); // object
console.log(x instanceof sum); // true;在这里,我们进入第二部分:我们如何才能真正理解function是否作为构造函数被调用?使用您上面提到的this instanceof行。基本上:
function sum(a, b) {
if (this instanceof sum) {
this.result = a + b;
} else {
return a + b;
}
}如果一个函数作为构造函数被调用,上下文对象this将指向刚刚创建的新对象。
此技术还用于在某些库中使用new-free语法,与您发布的代码类似,因此new是可选的:
var panel = Panel();在内部,他们只检查this
function Panel() {
if (this instanceof Panel) {
return this; // `new` operator was used
} else {
return new Panel(); // called without `new`, so we create a new object
}
}https://stackoverflow.com/questions/16021460
复制相似问题