javascript继承和instanceof运算符不一致
考虑构造函数函数:javascript继承和instanceof运算符不一致,javascript,instanceof,prototypal-inheritance,Javascript,Instanceof,Prototypal Inheritance,考虑构造函数函数: function ConstructorOne(){/*.....*/} function ConstructorTwo(){/*.....*/} 考虑以下js代码: var myInstance = new ConstructorOne(); ConstructorOne.prototype=new ConstructorTwo(); myInstance instanceof ConstructorOne; // false - why? myInstance inst
function ConstructorOne(){/*.....*/}
function ConstructorTwo(){/*.....*/}
考虑以下js代码:
var myInstance = new ConstructorOne();
ConstructorOne.prototype=new ConstructorTwo();
myInstance instanceof ConstructorOne; // false - why?
myInstance instanceof ConstructorTwo; // false - why?
如果我在将原型分配给构造函数后进行实例化,如下图所示,一切正常:
ConstructorOne.prototype = new ConstructorTwo();
var myInstance = new ConstructorOne();
myInstance instanceof ConstructorOne; // true
myInstance instanceof ConstructorTwo; // true
第一个例子中出现这种异常行为的原因是什么
以下是。因为在第一个示例中,您将一个新的原型对象分配给实例的构造函数。引述: 构造函数的对象实例
instanceof
操作符测试对象的原型链中是否存在构造函数.prototype
在此示例中:
var myInstance = new ConstructorOne();
ConstructorOne.prototype = new ConstructorTwo();
myInstance
prototype链(从\uuuuu proto\uuuuu
对象开始)包含ConstructorOne的旧(“默认”)原型。在使用第二行代码完全重写后,ConstructorOne.prototype
不再是myInstance
prototype链中的对象-因此false
作为instanceof
清晰解释的结果,非常感谢!