使用下面的代码,面向从斯托扬的JavaScript对象Stefanov`s 95页,如果你打电话的JavaScript面向的JavaScript
var my = new Triangle(5, 10);
my.toString()
你得到这样的结果采取。
"shape, 2D shape, Triangle"
我的问题与此代码中的第一个函数(函数Shape)有关。
1)我知道length
属性通常会做什么,但为什么它在代码result[result.length]
的function Shape
中很重要。如果代码返回字符串“形状,二维形状,三角形”的数组,它在哪里取名称的长度以及它在名称的长度上做了什么?
2)请问您能解释一下(用简单的语言)程序在说什么result[result.length]
?即结果中有结果。
由于
function Shape(){}
// augment prototype
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(){}
// take care of inheritance
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype;
// augment prototype
TwoDShape.prototype.name = '2D shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
// take care of inheritance
var F = function(){};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){return this.side * this.height/2;}