js中的继承

js继承

(es6之前的继承,es6继承之后补充)

1.使用构造函数来实现继承

实现方式 : 使用call等方法 使一个对象的this指向另一个对象 从而让其拥有这个对象的属性和方法

function Parent(name, age) {
    this.name = name;
    this.age = age;
    this.work = function () {
        console.log("挣钱养家");
    }
}
function Child(name, age) {
    Parent.call(this, name, age);
}
var c2 = new Child("amy", 12);
console.log(c2);	 // {name: "amy", age: 12, work: ƒ}
// 创建的child对象并不需要work方法 但是每次创建都会有(浪费空间)
c2.work();  // 执行了函数体

缺点:

1.无法继承父类原型上面的方法 对于子类不需要的方法 每次创建都会拥有 浪费内存空间
2.有很多构造函数的情况下 如果需要给所有的构造函数添加属性 那么就需要分别去加 就不便于维护

2.原型链继承

实现方法 : 利用原型链来实现继承 父类的一个实例化对象作为子类的原型

function Parent(name,age){
    this.name = name;
    this.age = age;
    this.work = function(){
        console.log("挣钱养家");
    }
}
// 原型上的属性 方法
Parent.prototype.test = function(){
    console.log(111);
}
Parent.prototype.type = "人类";

function Child(name,age){
    this.name = name;
    this.age = age;
}

Child.prototype = new Parent(); 
console.log(Child.prototype.constructor);   // Parent
// 重新替换原型后 构造函数并不指向原构造函数 所以要将构造函数指向原函数
Child.prototype.constructor = Child;
console.log(Child.prototype.constructor);   // Child

var c1 = new Child("zhangsan",12);
console.log(c1.type);
c1.test();

缺点 : 子类实例和父类实例的原型对象上有成员的共享问题

3.组合继承 原型链+call继承

通过这种组合的模式,实现了向父类构造传递参数,也可实现父类构造函数内属性和方法的多继承,但无法实现父类原型的多继承

function Father(){
    this.name = "父亲";
    this.run = function(){
        console.log(this.name + "我要跑步");
    }
}
Father.prototype = {
    constructor : Father,
    type : "人类",
    eat : function(){
        console.log(this.name + "我要吃饭");
    }
}
function Son(age){
    // 继承父类构造函数里面的属性或方法
    Father.call(this);
    this.age = age;
    this.study = function(){
        console.log(this.name + "我要学习");
    }
}
// 父类的一个实例化对象作为子类的原型
Son.prototype = new Father();
// 构造函数指向原函数
Son.prototype.constructor = Son;

Son.prototype.sleep = function(){
    console.log(this.name + "我要睡觉了");

}
var s1 = new Son(12);
// 这是父类构造函数里面的方法
s1.run();

// 父类原型里面的方法
s1.eat();
console.log(s1.type);

// 自己构造函数的方法
s1.study();

// 自己原型里的方法
s1.sleep();

你可能感兴趣的:(原生js)