How to create an object with private members using Object.create() instead of new

血红的双手。 提交于 2019-11-28 11:23:10

Yes, a init method on the prototype might be a more appropriate name:

var proto = {
    init: function(args) {
        // setting up private-scoped vars,
        var example = args;
        // privileged methods
        this.accessPrivate = function(){ return example; };
        // and other stuff
        this.public = 5;
    },
    prop: "defaultvalue",
    ...
}

var instance = Object.create(proto);
instance.init();

However, there is absolutely no reason not to use the classical constructor with the new keyword, which elegantly combines the Object.create and init call.

And note that you are using Object.create with absolutely no use. Your factory pattern (perfectly valid applied) returns good objects. No need to create new objects for each one that inherit from them. Just do:

var instance = trackQueue.factory();

If you like the sound of the method name "create", you might use a more idiomatic name for your factory:

trackQueueFactory.create = function(args) {...};

EDIT: Your idea to combine the factory pattern with prototype inheritance is not so wrong. Yet, the proto object from which all the fabricated objects inherit needs to be static, instead of creating a new one on each invocation. Your code might look like this:

var factory = {
    proto: {
        ...
    },
    create: function(args) {
        var product = Object.create(this.proto);
        // set up private vars scoped to the create function
        // privileged methods
        product.doSomethingSpecial = function(){ ... };
        // and other stuff
    }
};

var a = factory.create(...);

I think this is a clear way to achieve your requirements:

var personFactory = function(id, name, age){
    var _id = id;
    var _name = name;
    var _age = age;

    var personPrototype = {
        getId: function(){
            return _id;
        },
        setId: function(id){
            _id = id;
        },
        getName: function(){
            return _name;
        },
        setName: function(name){
            _name = name;
        },
        getAge: function(){
            return _age; 
        },
        setAge: function(age){
            _age = age;
        },
        work: function(){
            document.write(this.toString());
        },
        toString: function(){
            return "Id: " + _id + " - Name: " + _name + " - Age: " + _age;
        }
    };

    return Object.create(personPrototype);
};

Usage:

var renato = personFactory(1, "Renato Gama", 25);
console.log(renato.getName()); //logs "Renato Gama"
renato.setName("Renato Mendonça da Gama");
console.log(renato.getName()); //logs "Renato Mendonça da Gama"

If I am not wrong this is one the MODULE PATTERN usages. Refer to this post for a nicer explanation. This is also a good post about the subject.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!