2016-10-29 8 views
0

は、以下のコードを実行:コンストラクタのプロトタイプに関数を追加したにもかかわらず、なぜ「関数が未定義」になるのですか?

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."

のはなぜですArrayクラス/コンストラクタのプロトタイプに追加したにもかかわらず、last関数は未定義ですか?

+0

Mozillaは、ネイティブプロトタイプを拡張することは悪い習慣だと言っています。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain – cs01

+0

@ cs01ありがとうございました。それほど理解できない。 –

答えて

2

lastメソッドがプロトタイプに追加され、正しく実行されます。ここに問題はありません。

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

lastは不定であるため:

問題はlastコールがundefinedを返し、生成されたエラーは、この行のCannot read property 'toString' of undefinedであることです。

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

そしてまた、あなたがnewArray.first is not a functionエラーをavoildするプロトタイプにfirstメソッドを追加する必要があります:あなたはarrayの代わりに、ここでthisを使用するためです。

+0

ありがとうございました。 :-) –

+0

はい、私は意図的に何が起こるかを見るために 'newArray'に意図的に追加しませんでした。私はちょうど学ぶことを混乱させようとしています。 :-) –

+1

)あなたの研究で幸運 –

関連する問題