构造函数内部的构造函数 - 糟糕的做法? [英] constructor inside constructor - bad practice?

查看:177
本文介绍了构造函数内部的构造函数 - 糟糕的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在探索一些代码,我看到了将一个构造函数嵌入到另一个构造函数中的做法多次使用:

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)

您认为 phone_processor 构造函数应该在 contact_duplicates_manager 之外?

Do you think phone_processor constructor function should be outside contact_duplicates_manager?

推荐答案


您认为 phone_processor 函数构造函数应该在 contact_duplicates_manager 之外吗?

Do you think phone_processor function constructor should be outside contact_duplicates_manager?

是的。虽然有效和有效,但它效率低,可能不可读。通过嵌套,每个 contact_duplicates_manager 实例都具有 phone_processor s,具有不同的构造函数并继承自不同的原型对象。这可能是构造函数工厂或类似模式所必需的,但这些非常罕见,我怀疑你需要它。

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.

我的经验法则:



  • 将不需要访问任何本地闭包变量的每个函数移动到更高的范围。

  • 如果您不希望它在那里公开,请使用 IEFE

  • 如果您需要在多次执行函数范围内的构造函数,请尝试在构造函数之间共享原型对象,并且不要泄漏本地构造函数。

最后一条规则的示例:

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;
}

您不一定需要全局 Item 你调用类似继承的函数,有时是一个全局 proto 对象,你可以将它赋给 LocalConstructor.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.

这篇关于构造函数内部的构造函数 - 糟糕的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆