可以使用两种方式确定实例与原型之间的关系:
1. instanceof操作符
2. isPrototypeOf()方法
先来一段代码:
function SuperType(){
this.property = true;
}
//在SuperType函数的原型链上创建实例共享方法
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subProperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
return this.subProperty;
}
var instance = new SubType();
alert(instance.getSuperValue()); //true;
1. instanceof操作符
用这个操作符来测试实例与原型链中出现过的构造函数,如果有,就会返回true。或者说判断一个对象是不是另一个对象的实例。
a instanceof b; 如果a是b的实例就返回true
基于如上代码:
//instance 是Object的实例吗?
alert(instance instanceof Object); //true;
//instance 是SuperType的实例吗?
alert(instance instanceof SuperType); //true;
alert(instance instanceof SubType); //true;
2. isPrototypeOf()方法
只要是原型链上出现过的原型,都可以说是该原型链所派生的实例的原型,因此 isPrototypeOf()也会返回true。
//Object的原型在派生instance实例的原型链上?是的话就是instance实例的原型,返回true
alert(Object.prototype. isPrototypeOf(instance)); //true
//SuperType的原型在派生instance实例的原型链上吗?是的话就是instance实例的原型,返回true
alert(SuperType.prototype. isPrototypeOf(instance)); //true
//SubType的原型在派生instance实例的原型链上吗?是的话就是instance实例的原型,返回true
alert(SubType.prototype. isPrototypeOf(instance)); //true