JavaScript common objects are several ways to create: Object constructor, object literal pattern, plant pattern, custom constructor mode, plus prototype constructor combination mode; they each have their own advantages and disadvantages and usage scenarios.
1. Object Model constructor
- Usage scenarios: initial uncertain data within the object.
- Cons: Too many statements
var p = new Object()
p.name = 'tom'
p.age = 12
p.steName = function (name) {
this.name = name
}
2. The object literal mode
- Application scenarios: object data determined at the start.
- Cons: If you create multiple objects, duplicate code.
var p = {
name: 'jack',
age: 13,
setName: function (name) {
this.name = name
}
}
3. Factory Pattern
- Application scenario: the need to create multiple objects.
- Cons: object does not have a specific type of Object type.
function createPerson (name,age) { //返回一个对象的函数就是工厂函数
var obj = {
name: name,
age: age,
sstName: function (name) {
this.name = name
}
}
return obj
}
4. Custom Model constructor
- Usage scenarios: the need to create multiple types of objects identified.
- Disadvantages: Each object has the same data (method), a waste of memory.
function Person (name,age) {
this.name = name
this.age = age
this.setName = function (name) {
this.name = name
}
}
var p1 = new Person('tom',15)
var p2 = new Person('jack',14)
console.log(p1 instanceof Person) //true p1是Person类型
function student (name,grade) {
this.name = name
this.grade = grade
}
var s1 = new student('peter',6)
console.log(s1 instanceof student) //true s1是student类型
console.log(p1,p2)
p1 and p2 have each have the same setName () method, resulting in a waste of memory.
The prototype model constructor +
- Usage scenarios: To create multiple types of objects identified
function Person (name,age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
var p1 = new Person('tom',12)
var p2 = new Person('jack',13)
console.log(p1,p2)
Method of the object is placed on top of the prototype avoiding wasted memory.