我在多个 npm 包中发现了这部分代码:
function myClass (options) {
if (!(this instanceof myClass)) return new myClass(options);
...
}
查看 istanceof 运算符的定义:
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
为什么要在构造函数内部检查我正在创建的对象是否是此类的实例?我什么时候会得到“假”?
最佳答案
进行此检查是为了了解该方法是否是通过 new 运算符调用的。这样您就可以制作不同的场景,主要是初始化静态内容,或返回不同类型的对象。
function myClass (options) {
if (!(this instanceof myClass))
console.log ('not instance of');
else
console.log('instance of');
}
myClass('test'); // not instance of
new myClass('test'); // instance of
需要提及的一件重要事情 - new
运算符实际上返回一个新对象。所以
function MyClass(opts) {
}
var a = MyClass('a');
console.log(a); // undefined
它是未定义的,因为没有 return 语句。您只需执行一个函数,并将其结果分配给a
。但是,如果您使用 new
运算符(例如 var a = new MyClass('a');
),结果将为 myClass {}
.
关于javascript - JS : istanceof check inside constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604330/