This article mainly introduces the various ways and advantages and disadvantages of JavaScriptcreating objects. It mainly introduces 5 ways. If you are interested, you can learn about it
Written in front
This article explains Various ways of creating objects, with pros and cons.
But note:
This article is more like a note, because "JavaScript Advanced Programming" is so well written!
function createPerson(name) { var o = new Object(); o.name = name; o.getName = function () { console.log(this.name); }; return o; } var person1 = createPerson('kevin');
Disadvantages: Objects cannot be identified because all instances point to a prototype
2. ConstructorPattern
function Person(name) { this.name = name; this.getName = function () { console.log(this.name); }; } var person1 = new Person('kevin');
Advantages: Instances can be identified as a specific Type
Disadvantages: Every time an instance is created, each method must be created once
2.1 Constructor pattern optimization
function Person(name) { this.name = name; this.getName = getName; } function getName() { console.log(this.name); } var person1 = new Person('kevin');
Advantages: Solve the problem of each method having to be recreated
Disadvantages: This What is encapsulation called...
function Person(name) { } Person.prototype.name = 'keivn'; Person.prototype.getName = function () { console.log(this.name); }; var person1 = new Person();
Advantages: Methods will not be recreated
Disadvantages: 1. All properties and methodsare shared 2. Cannot initialize parameters
3.1 Prototype Pattern optimization
function Person(name) { } Person.prototype = { name: 'kevin', getName: function () { console.log(this.name); } }; var person1 = new Person();
Advantages: better encapsulation
Disadvantages: rewritten the prototype and lost the constructor attribute
3.2 Prototype mode optimization
function Person(name) { } Person.prototype = { constructor: Person, name: 'kevin', getName: function () { console.log(this.name); } }; var person1 = new Person();
Advantages: instances can find their constructors through the constructor attribute
Disadvantages: There are still some shortcomings of the prototype pattern
The constructor pattern and the prototype pattern are a perfect combination.
function Person(name) { this.name = name; } Person.prototype = { constructor: Person, getName: function () { console.log(this.name); } }; var person1 = new Person();
Advantages: Shared sharing, private private, the most widely used method
Disadvantages: Some people just want to write everything 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: When using the dynamic prototype mode, the prototype cannot be overridden with object literals
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('daisy'); // 报错 并没有该方法 person1.getName(); // 注释掉上面的代码,这句是可以执行的。 person2.getName();
To explain this problem, assume that var person1 = new Person('kevin') is started.
If you are not very familiar with the underlying execution process of new and apply, you can read the articles in the related links at the bottom.
Let’s review the implementation steps of new:
First create a new object
Then point the object’s prototype to Person.prototype
Then Person.apply(obj)
returns this object
Note at this time, review the implementation steps of apply, the obj.Person method will be executed, and the content in the if statement will be executed at this time. Note that the prototype attribute of the constructor points to the prototype of the instance, and uses literal method to directly override it. Person.prototype does not change the value of the prototype of the instance. person1 still points to the previous prototype, not Person.prototype. The previous prototype did not have a getName method, so an error was reported!
If you just want to write code in a literal way, you can try this:
function Person(name) { this.name = name; if (typeof this.getName != "function") { Person.prototype = { constructor: Person, getName: function () { console.log(this.name); } } return new Person(name); } } var person1 = new Person('kevin'); var person2 = new Person('daisy'); person1.getName(); // kevin person2.getName(); // daisy
5.1 Parasitic constructor pattern
function Person(name) { var o = new Object(); o.name = name; o.getName = function () { console.log(this.name); }; return o; } var person1 = new Person('kevin'); console.log(person1 instanceof Person) // false console.log(person1 instanceof Object) // true
The parasitic constructor pattern, I personally think it should be read like this:
Parasite-constructor-pattern, that is, a method that is parasitic on the constructor.
That is to say, under the guise of a constructor, you are trying to sell something like a sheep over someone else's head. You see, the created instance using instanceof cannot point to the constructor!
This method can be used in special situations. For example, if we want to create a special array with additional methods, but don’t want to directly modify the Array constructor, we can write like this:
function SpecialArray() { var values = new Array(); for (var i = 0, len = arguments.length; i len; i++) { values.push(arguments[i]); } values.toPipedString = function () { return this.join("|"); }; return values; } var colors = new SpecialArray('red', 'blue', 'green'); var colors2 = SpecialArray('red2', 'blue2', 'green2'); console.log(colors); console.log(colors.toPipedString()); // red|blue|green console.log(colors2); console.log(colors2.toPipedString()); // red2|blue2|green2
You will find that the so-called parasitic constructor pattern is actually better than the factory The pattern uses one more new when creating the object. In fact, the results of the two are the same.
But the author may hope to use SpecialArray like a normal Array. Although SpecialArray can be used as a function, this is not the author's intention and it becomes inelegant.
Do not use this mode when other modes can be used.
But it is worth mentioning that the loop in the above example:
for (var i = 0, len = arguments.length; i len; i++) { values.push(arguments[i]); }
can be replaced by:
values.push.apply(values, arguments);
5.2 The so-called stable constructor pattern
function person(name){ var o = new Object(); o.sayName = function(){ console.log(name); }; return o; } var person1 = person('kevin'); person1.sayName(); // kevin person1.name = "daisy"; person1.sayName(); // kevin console.log(person1.name); // daisy
object, It refers to an object that has no public properties and its methods do not reference this.
There are two differences from the parasitic constructor pattern:
The newly created instance method does not reference this
Does not use the new operatorto call the constructor
Safe objects are best suited for some safety environment.
The safe constructor pattern is also the same as the factory pattern and cannot identify the type of the object.
The above is the detailed content of An in-depth understanding of the many ways JavaScript creates objects and their pros and cons. For more information, please follow other related articles on the PHP Chinese website!