我一直在阅读很多关于JavaScript中的对象组合以及这种模式相对于'类的优点。图案。我已经看到了使用Object.create()
创建新对象的组合示例以及使用返回对象的工厂函数演示的其他示例。
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()
和返回对象的函数之间是否存在实际差异。
答案 0 :(得分:3)
工厂函数使用自己的属性创建对象,Object.create
创建分配了prototype的对象。
在您的示例中,ComponentFactory
创建的每个对象都有自己的init
(对内存中不同位置的引用),Object.create(Component)
创建对同一原型的对象引用({{1} })
Component
花费更少的空间/内存,因为它不会创建属性。将此用于对象的公共部分。
工厂函数更灵活,可以在closures中创建具有初始数据的对象和局部变量。将其用于对象的自定义部分。
Object.create
答案 1 :(得分:2)
<强>予。 Object.create
Object.create
从属性中给出的原型创建对象,因此如果我们检查hasOwnProperty
创建的对象Object.create
,我们将看到它没有属性(每个都在他的原型中) 。
因此Object.create(SomeObj)
创建的每个对象都与相同的原型链接,这会产生一些后果,例如原型中的复杂对象可以在每个实例上更改,并且更改在其他实例上可见。
结论 - Object.create类似于继承。
显示我在说什么的示例代码:
var obj={
complexProp:{
name:"John",
surname:"Doe"
},
hello:function(){
console.log("Hello "+this.complexProp.name+" "+this.complexProp.surname);
}
};
var objA=Object.create(obj);
var objB=Object.create(obj);
console.log(objA.hasOwnProperty("complexProp"));//false
objA.complexProp.surname="Smith";//change in objA
objB.hello();//so we see that change is also in objB
<强> II。工厂强>
第二个例子是动态创建对象,因此每个对象都是新实例,对象之间没有连接。第二个解决方案也给我们封闭,因此我们可以创建一些仅对我们的对象可见的私有变量或函数。私有变量用法:
var ComponentFactory = function(surname) {
var name="John";//local variable visible for object
return {
init: function() {
// do stuff
//variable name is visible in object
//variable surname is also visible from object
}
}
}
答案 2 :(得分:0)
正如其他人所提到的,Object.create()允许您创建具有某种关系的对象,而函数工厂则不允许。我实际上认为Object.create是工厂函数的一种形式,只是函数绑定到创建具有相同属性的对象。考虑以下两种情况:
的Object.create:
const Staff = {
setUp: function(name, idno){
this.name = name;
this.idno = idno;
this.office = "Unallocated"
this.category = "Staff";
this.accomodation = ""
}
};
james = Object.create(Staff);
james.setUp("James Black", 1)
console.log(james.name) //James Black
console.log(james.idno) //1
//Now let's assume that we want to change something about the 10,000 staff that //we recruit and sack every year. One condition is that all our staff are 20 //years old.
we simply say*/
Staff.age = 20
console.log(james.age)//20
&#13;
如您所见,您只需更改父对象即可更改组中所有成员的属性。但是,如果您使用的是每次只创建唯一对象的函数工厂,那么您将无法执行此操作。