Water Cooler v2 Water Cooler v2 - 1 month ago 9
Javascript Question

Why do I get a 'function is undefined' even though I added the function to the constructor's prototype?

Running the code below:

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);
}


Produces the following output:

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


All of which is fine except for the last line of the output, which says,
"last is undefined."


Why is the
last
function undefined even though I added it to the
Array
class/constructor's prototype?

Answer

Your last method is added to prototype and executed correctly. There is no problem here.

The problem is that last call returns undefined, and the error produced is Cannot read property 'toString' of undefined on this line:

console.log("last  = " + last.toString());

because last is undefined. This happens because you use array instead of this here:

last = function ()
{
  var len = this.length;
  if (len === 0) throw new Error("Empty array");
  return this[len - 1];
}

And also you need to add first method to prototype to avoild newArray.first is not a function error.