Home  >  Article  >  Web Front-end  >  Several ways to create js objects

Several ways to create js objects

王林
王林forward
2020-05-12 09:29:432615browse

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

Several ways to create js objects

# 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

Several ways to create js objects

#Problem: It solves the problem of factory pattern, but repeated creation in the same way wastes memory space.

4. Prototype pattern

Several ways to create js objects

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)

Several ways to create js objects

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete