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

前端 未结 2 1701
臣服心动
臣服心动 2020-12-10 16:45

EDIT: I figured it out from Bergi\'s answer in the end.

Thanks Bergi.

pubPrivExample = (function () {
    return {
        init : function () {
             


        
2条回答
  •  误落风尘
    2020-12-10 17:17

    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(...);
    

提交回复
热议问题