星空网 > 软件开发 > Java

Javascript继承实现

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();

Javascript继承实现

 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继承实现




原标题:Javascript继承实现

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Hero Deal:https://www.ikjzd.com/w/2238
AImotive:https://www.ikjzd.com/w/2239
Wayfair介绍_优势_入驻要求:https://www.ikjzd.com/w/224
Deep Instinct:https://www.ikjzd.com/w/2240
Kaymu:https://www.ikjzd.com/w/2241
Letstango.com:https://www.ikjzd.com/w/2242
TikTok 将推出先买后付服务 :https://www.kjdsnews.com/a/1836651.html
TikTok 将推出先买后付服务 :https://www.goluckyvip.com/news/188219.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流