选项 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
添加了方法,两者都有效。但这两个选项在创建对象时有什么区别吗?
最佳答案
使用选项 1,如果您创建 100 个 Gadget
,则会为内存中的每个对象创建 100 个 whatAreYou
函数。
使用选项 2,如果您创建 100 个 Gadget
,则内存中仅存在 1 个 whatAreYou
函数,每个 Gadget
都有一个指向该函数的链接通过 Gadget 的原型(prototype)实现功能
基本上使用原型(prototype)可以提高内存效率。
关于javascript - js中的put方法到function()和prototype有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17160081/