为什么 instanceof 运算符在确定对象类型时比构造函数 属性 更安全?
why instanceof operator safer than constructor property in determining object type?
当作者说:
The constructor property was originally intended for use in identifying the object type. However, the instanceof operator is considered to be a safer way of determining type
你能解释一下不使用 constructor
而不是 instanceof
来确定对象类型背后的问题是什么吗?
没有区别的传统示例可能是这样的:
car instanceof Car // true
car.constructor === Car // true
谢谢...
class A {
}
class B extends A {
}
var x = new B();
console.log('instanceof A', x instanceof A);
console.log('instanceof B', x instanceof B);
console.log('constructor = A', x.constructor === A);
console.log('constructor = B', x.constructor === B);
子类化有所作为