Create Object
- Literal way:
var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}}
Is new Object()
syntactic sugar, as the same.
- The factory pattern:
function createCar(){
var oTemp = new Object();
oTemp.name = arguments[0];
//直接给对象添加属性,每个对象都有直接的属性
oTemp.age = arguments[1];
oTemp.showName = function () {
alert(this.name);
};//每个对象都有一个 showName 方法版本
return oTemp;
};
var myHonda = createCar('honda', 5)
Just to new Object()
pack a layer of skin, easy to mass production, and there is no essential difference, tentatively regarded as a way to create objects.
- Constructor:
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.getName = function() {
return this.name;
};
}
var rand = new Person("Rand McKinnon", 33, "M");
The method getName constructor above, each instantiation of the function will create a new object also formed in the present case the eggs with no closure, it is a method of adding a constructor treated in the following manner, a method of adding to the subject when the factory mode should the following manner to avoid duplication object constructor
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.getName = getName
}
function getName() {
return this.name;
};
The process of creating an object constructor and factory pattern is just about the same, equivalent hides create a new object and return the object of these two steps, in the constructor this point to New object is no different.
The biggest difference: constructor created object constructor property points to the constructor, the factory model point function Object(){...}
.
Constructor prototype is equivalent to a plus chain ring, the prototype with its own constructor, factory pattern is a general function. Here I get a word of loopholes, constructor of the factory model to look at what is the point to which the first sentence of the new.
https://www.cnblogs.com/lihuanqing/p/7561480.html