JS继承

JS继承

伪类:通过构造一个人伪类来继承某个构造器。通过定义它的constructor函数并替换它的prototype为某个构造器的实例。(类的继承)

//构造器
var Mammal = function (name) {
    this.name = name;    
}
Mammal.prototype.get_name = function () {
    return this.name;  
}
Mammal.prototype.says = function () {
    return this.saying;  
}
//继承
var Cat = function (name) {
    this.name = name;
    this.saying = 'meow';      
}
//替换Cat.prototype为一个新的Mammal实例
Cat.prototype = new Mammal();

原型:新对象继承旧对象,通过创建一个对象并将其prototype指向目标原型对象。

// Object.creat
    Object.creat =function (o) {
        var F= function () {};
        F.prototype=o;
        return new F();     
    }
//对象
var myMammal ={
    name : ‘ bss’,
    get_name : function (){
        return this.name;
},
    says : function () {
        return this.saying || ' ';
},
}   
//继承对象
var myCat = Object.creat(myMammal);

 

posted @ 2018-02-03 20:32  白十三  阅读(131)  评论(0编辑  收藏  举报