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 @ 2016-07-11 17:13  goweb  阅读(142)  评论(0编辑  收藏  举报