如果我通过以下函数创建自定义对象:
function createCustomObject ( state ) {
let obj = { state };
obj.doSomething = function ( ) {
// do something
};
return obj;
}
let myNewObject = createCustomObject( { foo: 'bar' } );
myNewObject.doSomething();
这如何以记忆为目的? JavaScript是否为我创建的每个对象保留doSomething
方法的单独副本?如果我需要创建数千个对象,那么使用原型/组合会更有效吗?
答案 0 :(得分:0)
是的,将为每个呼叫创建一个新对象。
function createCustomObject ( state ) {
let obj = { state };
obj.doSomething = function() {};
return obj;
}
var o1 = createCustomObject();
var o2 = createCustomObject();
console.log(o1 === o2); // false
console.log(o1.doSomething === o2.doSomething); // false
如果你想分享方法,是的,最好使用原型继承。
function CustomObject ( state ) {
this.state = state;
}
CustomObject.prototype.doSomething = function() {};
var o1 = new CustomObject();
var o2 = new CustomObject();
console.log(o1 === o2); // false
console.log(o1.doSomething === o2.doSomething); // true