首页 > 更改对象原型后,为什么 instanceof 运算结果是false?

更改对象原型后,为什么 instanceof 运算结果是false?

function Rang(from, to){
    this.from = from;
    this.to = to;
}

Rang.prototype.include = function(x){
    return this.from < x && this.to > x;
}

var p1 = new Rang(3, 7);

Rang.prototype = {
    notInclude: function(){
        return this.from > x || this.to < x;
    }
}

console.log(p1 instanceof Rang);


//上述代码 为何最后控制台输入是false,求解释原因

你这里重写了原型对象,就切断了构造函数与最初原型之间的联系。

你可以看下《JavaScript高级程序设计》第六章的 6.2 创建对象,这一节下面的“原型的动态性”部分(第三版的书在P156),书上说的比较清楚了。


你在实例之后将Range的原型重写了,在判断实例,肯定会是false。因为此时Range.prototype的constructor指向的已经不是Range了。所以,需要重新设置Range.prototype.constructor=Range


【热门文章】
【热门文章】