Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript继承和instanceof运算符不一致_Javascript_Instanceof_Prototypal Inheritance - Fatal编程技术网

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
清晰解释的结果,非常感谢!