やりたいこと
prototypeプロパティを使って、オブジェクトにメソッドを追加しようとしています。
疑問点
Personオブジェクトに、身長から平均体重を計算するstdWeightメソッドを追加したいのですが、
lang
1 function Person(name, height) { 2 this.name = name; 3 this.height = height; 4 } 5 6 function calcWeight() { 7 var weight; 8 weight = (this.height - 100)*0.9; 9 return weight; 10 } 11 Person.prototype.stdWeight = calcWeight(); 12 13 var friends = new Array(3); 14 friends[0] = new Person("吉田直樹", 180); 15 friends[1] = new Person("吉田友菜", 100); 16 friends[2] = new Person("吉田桂子", 150); 17 18 for (i=0; i < friends.length; i++) { 19 document.write("<p>", friends[i].name, ":", friends[i].height ,"cm -> ", friends[i].stdWeight(), "kg</p>"); 20 }
prototypeプロパティを使ってPerson.prototype.stdWeight = calcWeight();
とすると、
標準体重を表示させる下記の部分で
document.write("<p>", friends[i].name, ":", friends[i].height ,"cm -> ", friends[i].stdWeight(), "kg</p>");
エラー「Uncaught TypeError: friends[i].stdWeight is not a function」が出ます。
Person.prototype.stdWeight = calcWeight;
とすると、うまく動作します。
これはどうしてでしょうか?自分なりに調べたのですが、スッキリと理解が出来ていません。基本的な内容で恐縮ですが、理由を教えてください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/03 13:55