Method 1: Object constructor pattern
- Create a step
- Create an empty Object and then dynamically add properties/methods
- Applicable scenario
- Initial uncertainty about the internal data of the object
- defects
- Statement is too much
/ / create a p
var p = new Object()
p.name = 'Tom'
p.age = '18'
p.setName = function (name) {
this.name = name
}
/ / test
p.setName('Jack')
console.log(p.name, p.age) // Jack 18
Copy the code
Method two: Object literal schema
- Create a step
- Create an object with {}, specifying properties/methods
- Applicable scenario
- The internal data of the object is determined at the beginning
- defects
- Duplicate code if you create multiple objects
/ / create a p
var p = {
name: 'Tom'.age: '18'.setName: function (name) {
this.name = name
}
}
/ / test
p.setName('Jack')
console.log(p.name, p.age) // Jack 18
Copy the code
Mode 3: Factory mode
- Create a step
- The factory function creates an object on the fly and returns it
- Applicable scenario
- Multiple objects need to be created
- defects
- Objects do not have a specific type. They are all Object types
function createPerson(name, age) {
var obj = {
name: name,
age: age,
setName: function (name) {
this.name = name
}
}
return obj
}
/ / test
var p1 = createPerson('Tom'.18)
var p2 = createPerson('Bob'.19)
console.log(p1.name, p2.age)
Copy the code
Method 4: Custom constructor schema
- Create a step
- Custom constructor that creates objects with new
- Applicable scenario
- Multiple objects of definite type need to be created
- defects
- Every object has the same data, wasting memory
function Person(name, age) {
this.name = name
this.age = age
this.setName = function (name) {
this.name = name
}
}
/ / test
var p1 = new Person('Tom'.18)
p1.setName('Jack')
console.log(p1.name, p1.age)
Copy the code
Method 5: constructor + prototype combination pattern
- Create a step
- Custom constructors, properties initialized in functions, methods added to prototypes
- Applicable scenario
- Multiple objects of definite type need to be created
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
/ / test
var p1 = new Person('Tom'.18)
p1.setName('Jack')
console.log(p1.name, p1.age)
Copy the code