码迷,mamicode.com
首页 > 编程语言 > 详细

javascript继承

时间:2014-05-23 06:33:35      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

 

 绑定构造函数


 

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

eg:

bubuko.com,布布扣
//父类
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 
bubuko.com,布布扣

 

 

使用prototype


 

 详细见:js-prototype

 

也使用prototype拷贝

准备拷贝函数:

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

 

eg:

bubuko.com,布布扣
//父类
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
bubuko.com,布布扣

 

 拷贝继承


 

 

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

 

详细见: js对象拷贝

 

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

javascript继承,布布扣,bubuko.com

javascript继承

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/wishyouhappy/p/3738232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!