使用下面的代碼,面向從斯托揚的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;}