使用下面的代码,取自 Stoyan Stefanov 的《面向对象的 JavaScript》第 95 页,如果您调用
var my = new Triangle(5, 10);
my.toString()
你会得到这个结果。
"shape, 2D shape, Triangle"
我的问题与此代码中的第一个函数(函数 Shape)有关。
1) 我知道什么length
属性(property)通常会这样做,但为什么它在这方面很重要function Shape
在代码中result[result.length]
。如果代码返回字符串数组“shape、2D shape、Triangle”,那么它在哪里获取名称的长度以及它对名称的长度做了什么?
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;}
最佳答案
result[result.length] = this.name;
这本质上是一种在数组的下一个可用位置(向前偏移)添加新片段的方法。
Javascript 中的数组从 0 开始,因此当添加第一个数组片段时,它实际上会执行以下操作:
result = [];
// result is empty, so result.length == 0
result[0] = this.name;
然后,当调用下一个 toString() 方法时,它将获取结果数组“length”(计数)并在该索引处创建一个新的数组片段:
// result has one piece, so result.length == 1
result[1] = this.name;
然后,当调用下一个 toString() 方法时,它将再次获取结果数组“length”(计数)并在该索引处创建一个新的数组片段:
// result has two pieces, so result.length == 2
result[2] = this.name;
这样你就有了一个包含三部分的数组,使用索引 0、1、2 或添加数组部分时结果数组部分的计数。
关于JavaScript 来自 Stoyan Stefanov 面向对象 JavaScript 的第 195 页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385953/