【问题标题】:javascript prototype constructor and instanceofjavascript原型构造函数和instanceof
【发布时间】:2013-07-17 13:29:08
【问题描述】:

当我检查instanceof方法时,结果不一样。

function A(){}
function B(){};

首先我将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 );

上面最后 4 个条件返回 true

但是当我尝试分配 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 );

在这种情况下 carA instanceof B 返回 false 。为什么它返回 false

【问题讨论】:

    标签: javascript jquery javascript-objects


    【解决方案1】:

    我从链接中找到答案 ..https://stackoverflow.com/a/12874372/1722625

    instanceof 实际检查左侧对象的内部[[Prototype]]。和下面一样

    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 ) ) 
    

    如果返回真,obj 就是instanceof B

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-07
      • 2014-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多