前端杂货随记

javascript继承之原型链继承(一)

2018-02-04  本文已影响5人  程序蜗牛

(一)原型链继承机制

基本思想是利用原型链继承另一个引用类型的属性和方法

function Car(){
    this.color = "黑色";// 汽车基础颜色
}

Car.prototype.changeColor = function(otherColor){
    // 提供更换颜色方法
    this.color = otherColor;
}
function Audi(master){
    this.master = master;
}
Audi.prototype = new Car();
Audi.prototype.getColor = function(){
    return this.color;
}
Audi.prototype.getMessage = function(){
    return this.master+"的奥迪颜色是"+this.color;
}
var car1 = new Audi("老王");
console.log(car1.getColor());// 黑色
console.log(car1.getMessage());// 老王的奥迪颜色是黑色

验证原型和实例之间的关系

console.log(car1 instanceof Object);// true
console.log(car1 instanceof Car);// true
console.log(car1 instanceof Audi);// true
console.log(Object.prototype.isPrototypeOf(car1));// true
console.log(Car.prototype.isPrototypeOf(car1));// true
console.log(Audi.prototype.isPrototypeOf(car1));// true

通过原型链实现继承时,不能使用对象字面量创建原型方法!!!

上一篇 下一篇

猜你喜欢

热点阅读