How to create JS objects

Keywords: Javascript

1, Literal measure

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

Problem: creating multiple objects can cause code redundancy and take up a lot of memory space.

2, Factory mode

function createToy(name) {
    var o = new Object();
    o.name = name;
    o.say = function() {
        console.log(this.name);
    }
    return o;
}
var toy1 = createToy('car');
toy1.say();
var toy2 = createToy('taxi');
toy2.say();
var toy3 = createToy('bus');
toy3.say();
console.log(toy1 instanceof Object);
console.log(toy2 instanceof Object);
console.log(toy3 instanceof Object);

Problem: Although the problem of creating object redundancy by object literal is solved, the problem of object recognition exists.

3, Constructor mode

function Toy(name) {
    this.name = name;
    this.say = function() {
        console.log(this.name);
    }
}
var toy1 = new Toy('car');
var toy2 = new Toy('car');
console.log(toy1.constructor);
console.log(toy2.constructor);
console.log(toy1.say === toy2.say); // false

Problem: solved the problem of factory mode, but the same method of repeated creation wasted memory space.

4, Prototype mode

function Person() {};
Person.prototype = {
    constructor: Person,
    name: 'mm',
    friends: ['mike','helen'],
    say: function() {
        console.log(this.name);
    }
}
var toy1 = new Person('train');
var toy2 = new Person('bus');
toy1.friends.push('suhai');
console.log(toy1.friends);
console.log(toy2.friends);

Problem: sharing method solves the problem of constructor. However, the properties of the reference type of the current instance are shared by all instances.

5, Combination mode (constructor + prototype mode)

function Person(name) {
    this.name = name;
    this.friends = ['mike','helen'];
};
Person.prototype = {
    constructor: Person,
    say: function() {
        console.log(this.name);
    }
}
var toy1 = new Person('train');
var toy2 = new Person('bus');
toy1.friends.push('suhai');
console.log(toy1.friends);
console.log(toy2.friends);

This is a common way to create.
The instance property is defined by constructor pattern, and the method and shared property are defined by prototype pattern.

Posted by Tyche on Sat, 25 Apr 2020 07:04:32 -0700