首页 > 代码库 > javascript继承
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。