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

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

时间:2016-09-01 10:51:30      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

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

标签:

原文地址:http://www.cnblogs.com/beyond-succeed/p/5828486.html

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