Difference <JavaScript> Constructor secure mode and a factory mode

Sound model constructor function code should look like this:
function Person(name, age, job) {
    var o = new Object();
 
    // private members
    var nameUC = name.toUpperCase();

    // public members
    o.sayName = function() {
        alert(name);
    };
    o.sayNameUC = function() {
        alert(nameUC);
    };

    return o;
}

var person = Person("Nicholas", 32, "software Engineer");

person.sayName(); // "Nicholas"
person.sayNameUC(); // "NICHOLAS"

alert(person.name);  // undefined
alert(person.nameUC);  // undefined

 


Those who want to set private members are not linked to the return of the property above the Person object o, is hung up in the public.
Of course, there are the private and public formal analogy from other OO language, the implementation principles or js in scope, closures and objects that set. Sense achieve quite clever.

Read the safe mode constructor, the constructor will understand sound mode and the factory pattern to create the difference objects.

Guess you like

Origin www.cnblogs.com/isAndyWu/p/11539630.html
Recommended