绑定构造函数
在子类构造函数中使用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