オプション1:
<script>
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}
var user = new Gadget('David', 'White');
console.log(user.whatAreYou());
</script>
オプション 2:
<script>
function Gadget(name, color) {
this.name = name;
this.color = color;
}
Gadget.prototype = {
whatAreYou: function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}
var user = new Gadget('David', 'White');
console.log(user.whatAreYou());
</script>
質問:
function()
オプション 1、メソッドを;に入れます。オプション 2、メソッドを追加しましprototype
た 、両方とも機能します。しかし、オブジェクトを作成するとき、これら 2 つのオプションに違いはありますか?