问题描述
我正在探索一些代码,我看到了将一个构造函数嵌入到另一个构造函数中的做法多次使用:
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
?
推荐答案
是的。虽然有效和有效,但它效率低,可能不可读。通过嵌套,每个 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_processor
s 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.
我的经验法则:
最后一条规则的示例:
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.
这篇关于构造函数内部的构造函数 - 糟糕的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!