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

Javascript继承实现

时间:2015-07-05 16:35:49      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

S1:js中一切皆对象,想想如果要实现对父对象属性和方法的继承,最初我们会怎样子来实现呢,考虑到原型的概念,最初我是这样来实现继承的

function Parent(){
   this.name=‘123‘;
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
console.log(‘Name :‘+son.getName()+‘;Age: ‘+son.getAge());


VM1777:16 Name :123;Age: 20

 从上面可以看到实现对Parent的继承主要是覆写了Son的prototype,这样便把Parent的属性和方法过给了Son的原型,这样子在通过new Son()构造出来的对象均会继承来自原型【即父对象Parent】的属性和方法,这样就达到了继承效果;但这样会带来一个副作用,就是当父对象中包含引用类型的属性时,子对象对引用类型数据的修改,会影响到所有的子对象,显然这不是我们需要的效果:

function Parent(){
   this.name=‘123‘;
   this.fruits=[‘apple‘];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push(‘pear‘);
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple", "pear"]

 S2:目前想到要解决这个问题就是使每个子对象都拥有一份父对象属性的复制品,这样修改属性时只是修改了子对象下的属性,而不会影响到其他的子对象属性。这一目标的实现参照前人的对象冒充的方式来实现

function Parent(){
   this.name=‘123‘;
   this.fruits=[‘apple‘];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push(‘pear‘);
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple"]

 上面我在Son函数里加了Parent.call(this)实现在new Son()的时候将this[即new 出来的Son对象]冒充成Parent函数里的上下文this来调用Parent()函数,从而拿到了父对象的属性和方法副本,所以在接下来修改父对象的属性和方法时其实是修改的副本,故达到了不会影响全部子对象的效果。但是由于Son.prototype=new Parent()的使用,我们得到了两份实例的属性和方法,而再我们拿到了副本以后,只是需要父对象的原型就行了,从下面可以看出我们只需要原型中的getname();

技术分享

 S3:接下来就是要去掉一份实例的属性和方法,这时候是constructor发挥作用的时候了,看下边代码,将Parent.prototype重新构建成一个原生对象,来作为子对象的原型,再把constructor指向子构造器

function Parent(){
   this.name=‘123‘;
   this.fruits=[‘apple‘];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
function Extend(Parent,Son){
   var proto = new Object(Parent.prototype);
   proto.constructor = Son;
   Son.prototype=proto;
}
Extend(Parent,Son);
Son.prototype.getAge=function(){
   return this.age;
}

 技术分享

Javascript继承实现

标签:

原文地址:http://www.cnblogs.com/oxf5deb3/p/4622038.html

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