js 原型链

146 阅读1分钟

一、原型链

function SuperType(){
    this.property = true;
}
SuperType.prototype.getSuperValue = function(){
    return this.property;
};
function SubType(){
    this.subproperty = false;
}
SubType.prototype = new SuperType();   //子类的原型指向父类的实例
SubType.prototype.getSubValue = function(){
    return this.subproperty;
};
var instance = new SubType();
console.log(instance.subproperty);   //false
console.log(instance.property);      //true
console.log(instance.getSubValue());  //false
console.log(SubType.prototype.property);   //true
console.log(SubType.prototype.getSuperValue());   //true


理解:把父类的实例赋给子类的原型,父类实例的属性和方法,父类原型上的方法,都将变为子类原型的属性和方法,是公共的。

二、检查哪些是来自原型的,哪些是来自实例的方法:

判断属性是否来自实例:instance.hasOwnProperty(‘property’);

判断属性是否来自原型:

此时先介绍一下in,property in instance:不管该属性(property)存在于实例中还是原型中,都会返回true。

判断属性是否来自原型的方法:

function hasPrototypeProperty(object,property){
    return !object.hasOwnProperty(property) && property in object;
}
console.log(instance.hasOwnProperty('subproperty'));
console.log(hasPrototypeProperty(instance,'subproperty'));
console.log(hasPrototypeProperty(instance,'property'));
console.log(hasPrototypeProperty(instance,'getSubValue'));
console.log(hasPrototypeProperty(instance,'getSuperValue'));


三、通过实例、构造函数访问原型的方法

//通过实例获取原型的方法
console.log('通过实例获取原型的方法');
console.log(instance.__proto__);
console.log(Object.getPrototypeOf(instance));
console.log(instance.prototype);     //undefined
//通过构造函数获取原型的方法
console.log('通过构造函数获取原型的方法');
console.log(SuperType.prototype);
console.log(SubType.prototype);

通过实例返问原型的方法:

instane.__proto__;

Object.getPrototypeOf(instance);

通过构造函数返问原型的方法:

构造函数.prototype;

四、确定原型和实例的关系

console.log(instance instanceof Object);
console.log(instance instanceof SuperType);
console.log(instance instanceof SubType);
console.log(Object.prototype.isPrototypeOf(instance));
console.log(SuperType.prototype.isPrototypeOf(instance));
console.log(SubType.prototype.isPrototypeOf(instance));

instanceof:只要用这个操作符来测试实例与原型链中出现的构造函数,结果都会返回true。

isPrototypeOf:只要原型链中出现过的原型都可以说是该实例的原型。

五、如何禁止修改原型中的方法