2011-03-22 68 views
0

使用下面的代码,面向从斯托扬的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;} 

回答

1
result[result.length] = this.name; 

这实质上是一种在下一个可用位置(偏移向前)向阵列中添加一块新块的方法。

在Javascript阵列从0开始,从而增加了第一阵列片时,它会在作用做到这一点:

result = []; 

// result is empty, so result.length == 0 
result[0] = this.name; 

然后,当下次toString()方法被调用时,它将采取的结果数组“长度”(计数),并创建索引处新阵列片:

// result has one piece, so result.length == 1 
result[1] = this.name; 

然后,当下次toString()方法被调用时,它会再次采取结果数组“长度”(计数)并在该索引处创建一个新的数组片:

// result has two pieces, so result.length == 2 
result[2] = this.name; 

因此,您有一个包含三个部分的数组,使用索引0,1,2或在添加数组部分时的结果数组碎片的计数。

1

该代码假定result将是连续的整数的键阵列。 length这样的数组将具有从0到length - 1的索引。因此,通过设置result[result.length] = something,会发生的情况是您将项目添加到该数组,并且新项目的索引比先前的最后一个索引高一个。

实际上,它将一个项目添加到数组中,同时保持索引编号连续,而不在项目索引之间留下任何空白空间。

0

数组的长度属性始终是最高索引加1,因此在数组[array.length]处添加一个项目会在数组末尾添加一个项目。

这相当于的Array.push(...),有时首选,因为一些(很)旧的浏览器不具有push方法,有时它的速度更快(有时它是慢)。