gpt4 book ai didi

javascript - 构造函数中的构造函数 - 不好的做法?

转载 作者:行者123 更新时间:2023-11-29 14:54:08 24 4
gpt4 key购买 nike

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

/**
* @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 function constructor should be outside contact_duplicates_manager?

是的。虽然有效且有效,但效率不高且可能不可读。通过嵌套,每个 contact_duplicates_manager 实例都有 phone_processor,它们具有不同的构造函数并继承自不同的原型(prototype)对象。这对于构造函数工厂或类似模式可能是必需的,但这些非常罕见,我怀疑您在这里需要它。

我的经验法则:

  • 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.

最后一条规则的例子:

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)就够了。

关于javascript - 构造函数中的构造函数 - 不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20784304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com