为什么我得到'函数未定义',即使我将该函数添加到构造函数的原型中?

时间:2016-10-29 06:52:48

标签: javascript

运行以下代码:

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类/构造函数的原型中?

1 个答案:

答案 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错误。