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

(一)原型链继承机制

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

  • 创建Car构造函数
function Car(){
    this.color = "黑色";// 汽车基础颜色
}

Car.prototype.changeColor = function(otherColor){
    // 提供更换颜色方法
    this.color = otherColor;
}
  • 创建Audi构造函数
function Audi(master){
    this.master = master;
}
  • Audi原型链继承Car
Audi.prototype = new Car();
  • 创建Audi原型链方法
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());// 老王的奥迪颜色是黑色

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

  • 第一种instanceof
console.log(car1 instanceof Object);// true
console.log(car1 instanceof Car);// true
console.log(car1 instanceof Audi);// true
  • 第二种isPrototypeOf
console.log(Object.prototype.isPrototypeOf(car1));// true
console.log(Car.prototype.isPrototypeOf(car1));// true
console.log(Audi.prototype.isPrototypeOf(car1));// true

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容