prototypeプロパティ



オブジェクトにメソッドを追加する


  • prototypeプロパティを使用してオブジェクトにメソッドを定義する


ソースコード【 HTML 】

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>prototypeによるメソッドの追加</title>

<script>

function Person(name, height){
  this.name = name;
  this.height = height;
  }

function calcWeight() {
  var weight;
  weight = (this.height - 100) * 0.9;
  return weight;
  }

Person.prototype.stdWeight = calcWeight;

</script>
</head>
<body>

<script>

var friends = new Array(3);

friends[0] = new Person('山田太郎',180);
friends[1] = new Person('田中一郎',175);
friends[2] = new Person('佐藤花子',160);

for(var i = 0;i <= friends.length -1;i++){
  document.write('<h1>',friends[i].name,':',
  friends[i].height,'cm の標準体重は、',
  friends[i].stdWeight(),'kg</h1>');
  }

</script>

</body>
</html>

ブラウザで表示