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

The use of progressbarcontrol, a progress bar control of devexpress – Taking ZedGraph as an example to add curve progress

scene WinForm control – devexpress18 download installation registration and use in vs: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100061243 When using ZedGraph to add curves, the number of curves is slower if there are many cases. So in the process of adding curve, the progress needs to be displayed, and the effect is as follows     Note: Blog home page:https://blog.csdn.net/badao_liumang_qizhi […]