`
风雪涟漪
  • 浏览: 496824 次
  • 性别: Icon_minigender_1
  • 来自: 大连->北京
博客专栏
952ab666-b589-3ca9-8be6-3772bb8d36d4
搜索引擎基础(Search...
浏览量:8764
Ae468720-c1b2-3218-bad0-65e2f3d5477e
SEO策略
浏览量:17660
社区版块
存档分类
最新评论

Javascript 继承 (三)

阅读更多

从子对象中访问父对象。

经典的面向对象语言都有语法可以在子类中访问父类,其实就是可以直接调用父类的引用。有的时候,我们在子类写一个方法,需要用到父类的方法时候,这个特性就格外有用了。在许多应用中,子类创建一个和父类相同的方法,并且在这个方法中调用父类的方法。在Javascript中并没有这个这种语法。但是很容易就能完成这个功能,让我们看如下的代码。

function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
var result = [];
if (this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
};

function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype;
TwoDShape.prototype.name = '2D shape';

function Triangle(side, height) {
this.side = side;
this.height = height;
}
var F = function(){};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){return this.side * this.height / 2;}

 新的不同在于

1.用uber的属性指向了父的prototype.

2.toString方法重写。

前一个例子中,toString方法返回了this.name,这个例子中首先检查this.constructor是否存在,存在的话就调用toString.this.constructor是函数自己本身。而this.constructor.uber指向了父的prototype.结果就是当调用Triangle实例的toString方法,所有的prototype链上的toString方法都被调用了。

var my = new Triangle(5, 10);
my.toString();//"shape, 2D shape, Triangle"

不要把uber并不是所谓的父类,意思就是不像其他面向语言的super或base之类的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics