1. Factory mode
function createPerson(name) { var o = new Object(); o.name = name; o.getName = function() { console.log(this.name) }; return o;}var person1 = createPerson(‘kevin‘)
Disadvantage: The object is not recognized because the instance is pointing to a prototype
2. Constructor mode
function Person(name) { this.name = name; this.getName = function() { console.log(this.name); }}var person1 = new Person(‘kevin‘)
Pros: Instances can be identified as a specific type
Cons: Every time you create an instance, each method is created once
2.1 Constructor Mode optimization
function Person(name) { this.name = name; this.getName = getName;}function getName() { console.log(this.name)}var person1 = new Person(‘kevin‘)
Pros: Resolves an issue where each method has to be recreated
Cons: What this is called encapsulation ...
3. Prototype mode
function Person(name) {}Person.prototype.name = ‘kevin‘;Person.prototype.getName = function() { console.log(this.name);}var person1 = new Person()
Pros: The method does not re-create
Cons: 1. All properties and methods are shared 2. Parameters cannot be initialized
3.1 Prototype mode optimization
function Person(name) {}Person.prototype = { name: ‘kevin‘, getName: function(){ console.log(this.name) }}var person1 = new Person()
Advantages: Better Encapsulation
Cons: Rewriting the prototype, missing the constructor property
3.2 Prototype Mode optimization
function Person(name) {}Person.prototype = { constructor: Person, name:‘kevin‘, getName: function() { console.log(this.name) }}var person1 = new Person()
Pros: Instances can find the owning constructor through the constructor property
Cons: The prototype model should have some drawbacks or
4. Combination mode
Combination of constructor mode and prototype mode
function Person(name) { this.name = name;}Person.prototype = { constructor: Person, getName: function() { console.log(this.name) }}var person1 = new Person()
Pros: The shared share, the private private, the most widely used way
Disadvantage: Some people just want to write all together, that is better encapsulation
4.1 Dynamic prototype mode
function Person(name) { this.name = name; if (typeof this.getName != ‘function‘) { Person.prototype.getName = function() { console.log(this.name) } }}var person1 = new Person()
Note: You cannot override a prototype with object literals when using dynamic prototype mode
Explain why:
function Person(name) { this.name = name; if (typeof this.getName != ‘function‘) { Person.prototype = { constructor: Person, getName: function() { console.log(this.name) } } }}var person1 = new Person(‘kevin‘)var person2 = new Person(‘marven‘)person1.getName() // 报错 并没有该方法person2.getName() // 注释掉上面的代码,这句是可以执行的
Several ways in which JavaScript deeply creates objects and their pros and cons