我一直在阅读很多关于 JavaScript 中的对象组合以及这种模式相对于“类”模式的优势的文章。我看过演示使用 Object.create()
创建新对象的组合示例,以及演示使用返回对象的工厂函数的其他示例。
对象创建示例:
var Component = {
init: function() {
// do stuff
}
};
var button = Object.create(Component);
button.init();
工厂函数示例:
var ComponentFactory = function() {
return {
init: function() {
// do stuff
}
}
}
var button = ComponentFactory();
button.init();
我知道工厂函数旨在抽象出创建对象所涉及的复杂性,但是我想了解 Object.create()
和返回 an 的函数之间是否有任何实际区别对象。
最佳答案
工厂函数创建具有自己属性的对象,Object.create
创建具有分配的 prototype 的对象.
在您的示例中,ComponentFactory
创建的每个对象都有自己的init
(引用内存中的不同位置),Object.create(Component)
创建引用同一原型(prototype)的对象 (Component
)
Object.create
占用更少的空间/内存,因为它不创建属性。将其用于对象的公共(public)部分。
工厂函数更灵活,可以用初始数据创建对象,局部变量在closures .将其用于对象的自定义部分。
const Component = {init() {}}
const x = Object.create(Component)
const y = Object.create(Component)
console.log(x.init === y.init) //true
function createComponent(data) {
return {
init() { return data }
}
}
const p = createComponent('a')
const q = createComponent('b')
console.log(p.init === q.init) //false
console.log(p.init()) //a
console.log(q.init()) //b
关于javascript - 工厂函数 vs Object.create - JavaScript - 何时使用哪个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39571915/