运行以下代码:
console.clear();
var array = [ 'Apples', 'Oranges', , 'Pear', ];
array.first = function()
{
var len = this.length;
if (len === 0) throw new Error("Array empty");
return array[0];
}
Array.prototype.last = function()
{
var len = this.length;
if (len === 0) throw new Error("Empty array");
return array[len - 1];
}
console.log("========================")
for(prop in array)
console.log(prop + " = " + array[prop].toString());
console.log("========================")
try
{
var first = array.first();
console.log("first = " + first.toString());
}
catch(e)
{
console.log(e.message);
}
try
{
var last = array.last();
console.log("last = " + last.toString());
}
catch(e)
{
console.log(e.message);
}
console.log("========================")
var newArray = [ 'a', 'b', 'c' ];
for(prop in newArray)
console.log(prop + " = " + newArray[prop].toString());
console.log("========================")
try
{
var first = newArray.first();
console.log("first = " + first.toString());
}
catch(e)
{
console.log(e.message);
}
try
{
var last = newArray.last();
console.log("last = " + last.toString());
}
catch(e)
{
console.log(e.message);
}
产生以下输出:
Console was cleared.
========================
0 = Apples
1 = Oranges
3 = Pear
first = function ()
{
var len = this.length;
if (len === 0) throw new Error("Array empty");
return array[0];
}
last = function ()
{
var len = this.length;
if (len === 0) throw new Error("Empty array");
return array[len - 1];
}
========================
first = Apples
last = Pear
========================
0 = a
1 = b
2 = c
last = function ()
{
var len = this.length;
if (len === 0) throw new Error("Empty array");
return array[len - 1];
}
========================
newArray.first is not a function
last is undefined
除了输出的最后一行("last is undefined."
为什么last
函数未定义,即使我将其添加到Array
类/构造函数的原型中?
答案 0 :(得分:2)
您的last
方法已添加到原型并正确执行。这里没有问题。
问题是last
调用返回undefined
,并且此行产生的错误为Cannot read property 'toString' of undefined
:
console.log("last = " + last.toString());
因为last
未定义。这是因为您在此处使用array
而不是this
:
last = function ()
{
var len = this.length;
if (len === 0) throw new Error("Empty array");
return this[len - 1];
}
此外,您还需要将first
方法添加到原型中以避免newArray.first is not a function
错误。