js几种继承方式

0.冒充继承
1.原型链继承
2.借用构造函数继承
3.组合继承
4.拷贝继承

今天看到了冒充继承

//1.把子类中共有的属性和方法抽取出,定义一个父类Stu 
function Stu(name, age){ 
    this.name = name; 
    this.age = age; 
    this.show = function(){ 
        window.alert(this.name + " " + this.age); 
    } 
} 
function MidStu(name, age) { 
    this.stu = Stu; 
    // 通过对象冒充来实现继承的 
    // 对象冒充的意思就是获取那个类的所有成员,因为js是谁调用那个成员就是谁的,这样MidStu就有了Stu的成员了 
    this.stu(name, age); 
    this.payFee = function(){ 
        window.alert("缴费" + money * 0.8); 
    } 
} 
function Pupil(name, age) { 
    this.stu = Stu; 
    // 通过对象冒充来实现继承的 
    this.stu(name, age); 
    this.payFee = function(){ 
        window.alert("缴费" + money * 0.5); 
    } 
} 

var midStu = new MidStu("zs", 13); 
midStu.show(); 
var pupil = new Pupil("ls", 10); 
pupil.show();

这些都不完美 最完美的如下

  function Animal(name, age) {
    this.name = name;
    this.age = age;
  };
  Animal.prototype.eat = function () {
    console.log('eat something');
  };

  function Dog(name, age, blood) {
    Animal.call(this, name, age);
    this.blood = blood;
  };

  function F() {
    //定义空函数
  }
  F.prototype = Animal.prototype;
  let f = new F();
  Dog.prototype = f;
  Dog.prototype.constructor = Dog;
  Dog.prototype.say = function () {
    console.log('wangwang');
  }
  let animal = new Animal('ljj',22)
  let erha = new Dog('erha', 1, '哈士奇');
  console.log(erha.name, erha.blood);
  erha.eat();
  erha.say();
  console.log(erha instanceof Dog,erha instanceof Animal)
  console.dir(erha)
  console.dir(animal)

还有一个别人写的一个比较整齐的版本:

// 父类

function supFather(name) {

    this.name = name;

    this.colors = ['red', 'blue', 'green']; // 复杂类型

}

supFather.prototype.sayName = function (age) {

    console.log(this.name, 'age');

};

// 子类

function sub(name, age) {

    // 借用父类的方法:修改它的this指向,赋值父类的构造函数里面方法、属性到子类上

    supFather.call(this, name);

    this.age = age;

}

// 重写子类的prototype,修正constructor指向

function inheritPrototype(sonFn, fatherFn) {

    sonFn.prototype = Object.create(fatherFn.prototype); // 继承父类的属性以及方法

    sonFn.prototype.constructor = sonFn; // 修正constructor指向到继承的那个函数上

}

inheritPrototype(sub, supFather);

sub.prototype.sayAge = function () {

    console.log(this.age, 'foo');

};

// 实例化子类,可以在实例上找到属性、方法

const instance1 = new sub("OBKoro1", 24);

const instance2 = new sub("小明", 18);

instance1.colors.push('black')

console.log(instance1) // {"name":"OBKoro1","colors":["red","blue","green","black"],"age":24}

console.log(instance2) // {"name":"小明","colors":["red","blue","green"],"age":18}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值