js继承方式

这个题目编辑了好久,一直都没来聊一聊。下面聊一下我理解的继承方法。

1.原型链继承

var Animal = function () {
    this.type = [];
};
var Cat = function () {
};

Cat.prototype = new Animal();
var cat1 = new Cat();
cat1.type.push("cat1");
var cat2 = new Cat();
cat2.type.push("cat2");

console.log(cat1.type); // ["cat1", "cat2"]
console.log(cat2.type); // ["cat1", "cat2"]

可见原型链继承中引用类型值得原型属性会被所有实例共享。


2.构造函数继承

var Animal = function () {
    this.type = [];
};
var Cat = function () {
    Animal.call(this);
};

var cat1 = new Cat();
cat1.type.push("cat1");
var cat2 = new Cat();
cat2.type.push("cat2");

console.log(cat1.type); // ["cat1"]
console.log(cat2.type); // ["cat2"]
构造函数继承虽然解决了上面的问题,但是每个实例会重新new一下方法,不会共享方法。
 
3.组合继承
var Animal = function (name) {
    this.name = name;
    this.type = [];
};
Animal.prototype.sayName = function () {
  console.log(this.name);
};
var Cat = function (name, voice) {
    Animal.call(this, name);
    this.voice = voice;
};
Cat.prototype = new Animal();
Cat.prototype.say = function () {
    console.log(this.voice);
};

var cat1 = new Cat("小花", "喵喵1");
cat1.type.push("cat1");
var cat2 = new Cat("小红", "喵喵2");
cat2.type.push("cat2");

console.log(cat1.type); // ["cat1"]
console.log(cat2.type); // ["cat2"]
cat1.sayName(); // 小花
cat1.say(); // 喵喵1
cat2.sayName(); // 小红
cat2.say(); // 喵喵2

组合继承融合了原型和构造函数组合继承的优势,实现了属性私有,方法共享。是最常用的继承方式。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值