[英]javascript prototype constructor and instanceof
When I checked instanceof
method, the results are not same . 当我检查instanceof
方法时,结果并不相同。
function A(){}
function B(){};
First I assigned prototype
( reference ) property , into A
首先,我将prototype
(参考)属性分配给A
A.prototype = B.prototype;
var carA = new A();
console.log( B.prototype.constructor );
console.log( A.prototype.constructor == B );
console.log( B.prototype.constructor == B );
console.log( carA instanceof A );
console.log( carA instanceof B );
The last 4 condition on above returns true
. 上面的最后4个条件返回true
。
But when I tried to assign constructor
of B .. results are not same . 但是当我尝试分配B ..的constructor
,结果不一样。
A.prototype.constructor = B.prototype.constructor;
var carA = new A();
console.log( B.prototype.constructor );
console.log( A.prototype.constructor == B );
console.log( B.prototype.constructor == B );
console.log( carA instanceof A );
console.log( carA instanceof B );
On this case carA instanceof B
returns false
. 在这种情况下, carA instanceof B
返回false
。 Why it returns false 为什么返回假
I found answer from link .. https://stackoverflow.com/a/12874372/1722625 我从链接中找到了答案.. https://stackoverflow.com/a/12874372/1722625
instanceof
actually checking internal [[Prototype]]
of left-hand object . instanceof
实际上检查左手对象的内部[[Prototype]]
。 Same like below 像下面一样
function _instanceof( obj , func ) {
while(true) {
obj = obj.__proto__; // [[prototype]] (hidden) property
if( obj == null) return false;
if( obj == func.prototype ) return true;
}
}
// which always true
console.log( _instanceof(carA , B ) == ( obj instanceof B ) )
if it returns true, obj
is instanceof
B 如果返回true,则obj
是B的instanceof
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.