Home > Article > Web Front-end > Several ways to create js objects
1. Literal method
var obj = { name: 'mm', age: 18, sayName: function() { console.log(this.name); } }
Problem: Creating multiple objects will cause code redundancy and occupy a lot of memory space.
2. Factory Mode
# Problem: Although the problem of object literals creating object redundancy is solved, there is still the problem of object recognition. It cannot reflect the internal relationship between them.
3. Constructor pattern
#Problem: It solves the problem of factory pattern, but repeated creation in the same way wastes memory space.
4. Prototype pattern
Problem: Shared methods solve the problem of constructors. However, the reference type properties of the current instance are shared by all instances, and one variable changes everything.
5. Combination mode (constructor prototype mode)
This is a commonly used creation method.
Define instance properties through the constructor pattern, and define methods and shared properties through the prototype pattern.
Recommended tutorial: js introductory tutorial
The above is the detailed content of Several ways to create js objects. For more information, please follow other related articles on the PHP Chinese website!