javascript继承

 

 绑定构造函数


 

在子类构造函数中使用Fatherconstructor.apply(this, arguments)

eg:

//父类
function People(name,age){
    this.name = name;
    this.age = age;
    this.species = "human";
    this.getName = function(){
        return this.name;
    }
    this.getAge = function(){
        return this.age;
    }
    this.sayHello = function(){
        console.log("hi,I am the father class");
    }
}

//子类
function Children(name,age){    
    People.apply(this,arguments)
}

var wish = new Children("wish");
console.log("the name of wish is:"+wish.getName());  //the name of wish is:wish 
console.log(wish.sayHello());  //hi,I am the father class 

 

 

使用prototype


 

 详细见:js-prototype

 

也使用prototype拷贝

准备拷贝函数:

function extend(Child, Parent){
    var parent = Parent.prototype;
    var child = Child.prototype;
    for(var i in parent){
        child[i] = parent[i];
    }
    child.uber = parent; //备用性质,指向上一层
}

 

eg:

//父类
function People(){
}
People.prototype.sayHello = function(){
    return "hello";
}
People.prototype.getName = function(){
    return this.name;
}
People.prototype.getAge = function(){
    return this.age;
}

//子类
function Children(name, age){
    this.name = name;
    this.age = age;
}

//定义拷贝函数

function extend(Child, Parent){
    var parent = Parent.prototype;
    var child = Child.prototype;
    for(var i in parent){
        child[i] = parent[i];
    }
    child.uber = parent; //备用性质,指向上一层
}

//子类

extend(Children, People);
var wish = new Children("wish","20");
console.log(wish.getName());  //wish
console.log(wish.getAge());  //20
console.log(wish.sayHello());  //hello

 

 拷贝继承


 

 

function deepCopy(p, c) {
    var c = c || {};
    for (var i in p) {
      if (typeof p[i] === ‘object‘) {
        c[i] = (p[i].constructor === Array) ? [] : {};
        deepCopy(p[i], c[i]);
      } else {
         c[i] = p[i];
      }
    }
    return c;
}

 

详细见: js对象拷贝

 

参考:http://www.ruanyifeng.com/blog

javascript继承,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。