Common object creation modes

Time:2019-11-5

1. Object constructor

var obj = new Object();
        obj.name = 'tom';
        obj.age = 15;
        obj.sayName = function() {
            console.log(this.name)
        }

The disadvantage of this method is obvious, that is to write a lot of code.

2. Object literal creation

var obj1 = {
name: 'tom',
age: 15,
sayName: function() {
console.log(this.name)
}
}
var obj2 = {
name: 'jock',
age: 18,
sayName: function() {
console.log(this.name)
}
}

The disadvantage of literals is that when we create multiple similar objects, it is still not flexible enough and will still generate duplicate code.

3. Factory mode

function person(name, age) {
            var obj = {
                name: name,
                age: age,
                sayName: function() {
                    console.log(this.name)
                }
            }
            return obj
        }
console.log(person(‘tom’, 18))
console.log(person(‘jony’, ’19’))

The problem with factory functions is that there is no specific type for the objects it creates. All objects created through factory functions are of object type

4. Constructor method

function Person(name, age) {
            this.name = name;
            this.age = age;
            this.setName = function(name) {
                this.name = name
            }
        }
        var p1 = new Person('tom', 16);
        var p2 = new Person('jony', 18);
        console.log(p1)
        console.log(p2)

The object code created by constructor method is simple enough, and the created object has its own class. However, when we create multiple objects at the same time, we will find that the created objects contain the same method, which is a waste of memory.

5. Constructor plus prototype

function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype.setName = function(name) {
            this.name = name
        }

We extend the constructor’s method to its prototype, so there is no need to create multiple methods at the same time when creating objects.

 

The above is a common way to create objects that I know. I’d like to record it in this article. Please point out any mistakes!

Recommended Today

Common commands and differences between find and grep under Linux

When using Linux, you often need to find files. The main search commands are find and grep. There is a difference between the two commands.  Difference: (1) The find command is to find the file according to its attributes, such as file name, file size, owner, group, whether it is empty, access time, modification time, […]