js create objects of several models

 

Factory Pattern

    function createPerson(name, age) {
        let o = new Object();
        o.name = name
        o.age = age
        o.say = function() {
            console.log("name", this.name, "age", this.age);
        }
        return o
    }
    let object1 = createPerson('n1', 'a1');
    let object2 = createPerson('n2', 'a2');
    object1.say();
    object2.say();

 

    This factory function call, passing the name and age each time one of the two properties and returns an object comprising a method of

 

Constructor

    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.say = function () {
            console.log("name", this.name, "age", this.age);
        }
    }
    let p1 = new Person('n1', 'a1');
    let p2 = new Person('n2', 'a2');
    p1.say();
    p2.say();

 

In fact, you can see in the constructor returns an object of no return. However, these are some of the automatic operation using the new operator.

(1) create a new object

(2) This new object will be bound to this function call

(3) Object Returns

 

Prototype mode

    function Person() {
    }
    Person.prototype.name = 'name'
    Person.prototype.age = 'age'
    Person.prototype.say = function () {
        console.log(this.name, this.age);
    }
    let p = new Person()
    p.say();

 

The benefits of using the prototype is that it gives all the instances shared objects it contains properties and methods, do not have the information in the constructor defined object instance.

Guess you like

Origin www.cnblogs.com/chenmz1995/p/12094310.html