js中的继承

1.拷贝继承

//创建一个父类的构造器
function CreatePerson(name,sex){//父类
    this.name=name;
    this.sex=sex;
}

//给父类添加showName方法
CreatePerson.prototype.showName=function(){
    alert(this.name);
}

var p1 = new CreatePerson("小名","男");
// p1.showName();


function CreateStar(name,sex,job){
    //调用父类的构造方法,不必重写已有的属性
    //call()方法第一个参数为this的指向,后面的为要传入的参数列表.
    //继承父类的属性
    CreatePerson.call(this,name,sex);
    //新增自己的属性.
    this.job = job;
}
//对原型链上的方法进行拷贝继承
extend(CreateStar.prototype,CreatePerson.prototype);

//在子类的原型链上新增自己的方法
CreateStar.prototype.showJob=function(){
    alert(this.job);
}

//重写父类的方法,当子类有次方法时不会去调用父类的方法.
CreateStar.prototype.showName = function(){
    console.log(this.name);
}

//实例化一个子类
var p2 = new CreateStar("黄晓明","男","演员");
p2.showName();//黄晓明 console
p2.showJob();//演员    alert

//拷贝
function extend(obj1,obj2){
    for(var attr in obj2){
        obj1[attr]=obj2[attr];
    }
}

2.原型继承:

var a ={
    name:"小明"
};



var b = cloneObj(a);

b.name="小强";

alert(a.name);

function cloneObj(obj){

    var F = function(){};

    F.prototype = obj;

    return new F();
}

3.类式继承:

function Aaa(){//父类
    this.name=[1,2,3];
}

Aaa.prototype.showName = function(){
    alert(this.name);
}

//继承父类的属性
function Bbb(){//子类
    Aaa.call(this);
}

//创建一个第三方构造器
var F = function(){};
//修改F的原型
F.prototype = Aaa.prototype;

Bbb.prototype = new F();
Bbb.prototype.constructor = Bbb;//修正指向问题


//像下面这样简单粗暴的写法是错的,因为这样写,会修改父类原型上的方法.
// Bbb.prototype = Aaa.prototype;
// Bbb.prototype.constructor = Bbb;
// Bbb.prototype.showName=function(){
//     console.log(this.name);
// }
// var a1 = new Aaa();
// a1.showName();//此时会console,而不是alert


var b1 = new Bbb();
b1.name.push(4);
b1.showName();//1,2,3,4
alert(b1.constructor);
var b2 = new Bbb();
alert(b2.name);//1,2,3

 4.prototypal

类似于拷贝继承.
var
human = { species:"human", create:function(values){ var instance = Object.create(this); //Object.keys({a:1,b:2})=> ["a","b"]; Object.keys(values).forEach(function(key){ instance[key] = values[key]; }); // instance.name = name; return instance; }, saySpecies:function(){ console.log(this.species); }, sayName:function(){ console.log(this.name); } } var musician = human.create({ species:'musician', playInstrument:function(){ console.log("play..."+this.instrument); } }); var will = musician.create({ name:"will", instrument:"Gitar" });

 

posted on 2017-02-05 16:32  夜行锦衣  阅读(86)  评论(0编辑  收藏  举报

导航