Create a custom object methods
The factory pattern:
function createPerson (name, obj, job) {
var o = new Object()
o.name = name
o.sayName = function () {
alert(this.name)
}
return o
}
Disadvantages: does not solve the problem of object recognition.
2. Constructor
function Person (name, age, job) {
this.name = name
this.age = age
this.job = job
this.sayName = function () {
alert(this.name)
}
}
Advantages: solve the problem of object recognition
Disadvantages: sharing method is not implemented
3. prototype model
function Person () {}
Person.prototype.name = 'four o'clock'
Person.prototype.job = 'front end'
Person.prototype.sayName = function () {
alert(this.name)
}
Pros: to achieve a shared method, but also avoid the problem of object recognition
Cons: Unable to pass initialization parameters, the method is not only shared, all of the properties are also shared, changed one instance, all instances are likely to be affected.
4. prototype model constructor +
function Person (name, age, job) {
this.name = name
this.age = age
this.job = job
}
Person.prototype = {
constructor: Person,
sayName: function () {
alert(this.name)
}
}
Advantages: object recognition to solve the problem. Solve shared property.
Cons: None.
4. parasitic Constructor
function SpecialArray (name, job, age) {
var values = new Array()
values.push.apply(values, arguments)
values.toPipedString = function () {
return this.join('|')
}
return values
}
Advantages: can not affect the basis of the original objects (the Array) on the extended
Disadvantages: can not determine an object type, and examples of constructors and no relationship
The sound Constructor
function Person (name, age, job) {
var o = new Object()
o.sayName = fucntion () {
alert(name)
}
return o
}
var friend = Person ( 'four o'clock', 29, 'front end')
firend.sayName()
Pros: In addition to calling sayName methods, not gain access to the raw data passed to the constructor of the members. Do not use this, no operations using the new operator constructor
Disadvantages: still can not identify the object.