选项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>
问题:
选项1,我将方法放入function()
;选项2,我通过添加方法prototype
,它们都有效。但是在创建对象时这两个选项有什么不同吗?