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

Several ways to create js objects

王林
Release: 2020-05-12 09:29:43
forward
2696 people have browsed it

Several ways to create js objects

1. Literal method

var obj = {
    name: 'mm',
    age: 18,
    sayName: function() {    
        console.log(this.name);
    }
}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template