javascript備忘録

備忘録:2 プロトタイプオブジェクト

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>0611javascript</title>
<script type="text/javascript">
コンストラクタで初期化する
var Member = function(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
this.getName = function(){
return this.lastName + '' + this.firstName;
}
};
var men = new Member('kenji','morita');
document.write(men.getName());

動的メソッドを追加する

var Menber2 = function(lastname,firstname){
this.lastName = lastname;
this.firstName = firstname;
};
var men2 = new Menber2('kenji','morita');
men2.getName = function (){
return this.lastName + ':' + this.firstName;
}
alert(men2.getName());

 

プロトタイプオブジェクト
var Membber = function(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
};
Membber.prototype.getName = function(){
return this.lastName + ':' + this.firstName;
};

var men = new Membber('fujimaki','takashi');
var men2 = new Membber('morita','kenji');
document.write(men.getName());
document.write('<br>');
document.write(men2.getName());
</script>
</head>
<body>
<p>fafafa</p>
</body>
</html>