javascript --- 子对象访问父对象的方式

  在传统面向对象的编程语言里,都会提供一种子类访问父类的特殊语法,引文我们在实现子类方法往往需要父类方法的额外辅助。在这种情况下,子类通常会调用父类中的同名方法,最终以便完成工作。

javascript虽然没有类似上述的特殊语法,但我们可以造一个啊!

function her(){};
her.prototype.name = 'Anna';
her.prototype.toString = function(){
    var const = this.constructor;
    return   const.uber ? this.const.uber.toString() + ',' + this.name :   this.name;
}

function his(){};
var F = function(){};
F.prototype = her.prototype;
his.prototype = new F();
his.prototype.constructor = her;
his.uber = her.prototype;
his.prototype.name  ='Jock';

function child(width, height){
    this.width = width;
    this.height = height;
}
var F = function(){};
F.prototype = his.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.uber = his.prototype;
child.prototype.name = 'Los';
child.prototype.getArea = function(){
    return this.width * this.height;
}

我们在构建关系的过程中,我们引入了一个uber属性,并令其指向父及对象。

在这里,我们更新了以下内容:

  1. 将usber属性设置成指向父对象的引用;

  2. 对toString()方法进行了更新;

之前的toString()方法只是简单的返回this.name,现在我们给他添加了额外的任务,就是检查this.constructor.usber属性,如果存在就调用该属性的toString()方法。

由于this.constructor本身是一个函数,而this.constructo.usber是指向当前对象父级原型的引用,所以我们调用child实体的toString()方法时,其原型链上的toString()方法都会被调用。

var my  = child(1,2);
my.toString() // Anna, Jock, Los

 

转载于:https://www.cnblogs.com/beyond-succeed/p/5828486.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值