js中的继承

1、原型继承

原型继承的特点:即继承了父类的模版,又继承了父类的原型对象

复制代码
// 父类
function Person(name, age) {
    this.name = name;
    this.age = age;
}
// 父类的原型对象方法
/*Person.prototype.say = function() {
    console.log('hello');
}*/

Person.prototype = {
    constructor: Person,
    say: function (){
        console.log(this.name)
    }
}

// 子类
function Boy(sex) {
    this.sex = sex;
}
Boy.prototype = new Person('zn',18);
var b = new Boy();
console.log(b.name);
console.log(b.age);
b.say();
复制代码

2、类继承(只继承模版, 不继承原型对象) (借用构造函数的方式继承)

复制代码
// 父类
function Person(name, age) {
    this.name = name;
    this.age  = age;
}
// 父类的原型对象属性
Person.prototype.id = 1;

// 子类
function Boy(name, age, sex) {
    // call apply
    Person.call(this, name, age);
    this.sex = sex;
}
var b = new Boy('张三', 20, '男');
console.log(b.name);
console.log(b.age);
console.log(b.sex);
console.log(b.id);
复制代码

3、混合继承(借用构造函数继承 + 原型继承)

复制代码
// 父类
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.id = 1;

Person.prototype = {
    constructor: Person;
    sayName: function () {
    console.log(this.name);
}
}
// 子类
function Boy(name, age, sex) {
    // 借用构造函数继承
    Person.call(this, name, age);
    this.sex = sex;
}
// 原型继承
//继承父类的原型对象
Boy.prototype = new Person();
var b = new Boy('zn', 18, '男');
console.log(b.name);
console.log(b.sex);
console.log(b.age);
b.sayName();
复制代码

4、ES5 提供的create方法 在实际开发过程中为了兼容低版本浏览器做出继承方法如下封装

复制代码
var create = function(obj) {
    //(火狐 谷歌等)
    if (Object.create) {
        return Object.create(obj);
    }
    else {
        //(ie 低版本)
        function F() {}
        F.prototype = obj;
        return new F();
    }
}
复制代码

 

posted @   goweb  阅读(146)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示