Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - constructor inside constructor - bad practice?

I'm exploring some code and I saw the practice of embedding one constructor function into another used many times:

/**
 * @constructor
 */
function contact_duplicates_manager(global_objects)
{
    this.field_processors =
    {
        "Phone1Number": new phone_processor(),
        "Phone2Number": new phone_processor(),
        "Phone3Number": new phone_processor()
    }
    //...here some other code

    /**
     * @constructor
     */
    function phone_processor()
    {
        //...here some other code

        function clear_phone(phone)
        {
            //...here some code
        }
        this.is_equals = function (value1, value2) 
        {
            return is_equals(clear_phone(value1), clear_phone(value2));
        }
    }
}

//... later in the code
var valid = this.field_processors[fld_name]["is_equals"](native_value, custom_value)

Do you think phone_processor constructor function should be outside contact_duplicates_manager?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you think phone_processor function constructor should be outside contact_duplicates_manager?

Yes. While being valid and working, it's not efficient and possibly unreadable. With the nesting, every contact_duplicates_manager instance has phone_processors with different constructors and inheriting from a different prototype object. This might be necessary for constructor factories or similar patterns, but those are very rare and I doubt you need it here.

My rules of thumb:

  • Move every function that does not need access to any local closure variable to a higher scope.
  • If you don't want it to be public in there, use an intermediate scope of an IEFE.
  • If you need a constructor inside the scope of a multiple-times-executed function, try to share the prototype object among the constructors, and do not leak a local constructor.

An example for the last rule:

function Item(…) {…}
function Store {
    var that = this;
    this.items = [];
    this.addItem = function(…) {
        that.items.push(new LocalItem(…));
    };
    function LocalItem(…) {
        Item.call(this, …);
        this.store = that;
    }
    LocalItem.prototype = Item.prototype;
}

You don't necessarily need the global Item function which you call inheritance-like, sometimes a single global proto object which you can assign to LocalConstructor.prototype is enough.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...