我有这个模块
var MF = (function() { // module pattern start
function MF(selector) {
if (!(this instanceof MF))
return new MF(selector); // always construct
this.node = null; // expose your DO
if (typeof selector === 'string') {
switch (selector.substring(0, 1)) {
case '#':
this.node = document.getElementById(selector.substring(1));
break;
case '.':
this.node = document.getElementsByClassName(selector.substring(1).replace('.', ' '));
break;
default :
this.node = document.getElementsByTagName(selector);
break;
}
if (this.node.length > 1) {
return MFList(this.node);
} else if (typeof this.node.length !== 'undefined') {
return MF(this.node[0]);
}
} else if (selector instanceof HTMLElement) {
this.node = selector;
}
}
function isArraylike(obj) {
var length = obj.length;
return (length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj);
}
function MFList(List) {
var _List = [];
MF.foreach(List, function(k, v) {
_List[k] = new MF(v);
});
return _List.length > 0 ? _List : false;
};
MF.prototype.foreach = function(obj, callback) {
var value,
i = 0,
isArray = isArraylike(obj);
if (isArray) {
var length = obj.length;
for (; i < length; i++) {
value = callback.call(obj[ i ], i, obj[ i ]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[ i ], i, obj[ i ]);
if (value === false) {
break;
}
}
}
return obj;
}
return MF; // pass refence out
}()); // module pattern end
我不得不承认,JavaScript 的对象模型对我来说相当困惑。我收到的错误是它无法识别函数 MFList
中的 MF.foreach
。我不太清楚实例如何使用此模块模式,但如果有人能告诉我如何在对象的私有(private)函数内调用 MF.foreach ,我会非常高兴?谢谢!
最佳答案
The error I'm getting is that it doesn't recognize
MF.foreach
in functionMFList
.
对。函数MF
没有名为 foreach
的属性。通过函数 MF
创建的对象有一个名为 foreach
的属性(当您执行 new
时,它们从通过 new MF(...)
运算符分配的原型(prototype)中获取它)。
如果你想要MF
本身具有该功能,而不是由它创建的具有该功能的对象,您需要更改
MF.prototype.foreach = ...
至
MF.foreach = ....
MF.prototype
用于设置通过 new MF
创建的对象的原型(prototype);您放在那里的属性与 MF
没有其他联系功能。
旁注:我强烈建议重构 MF
功能。您将它用作构造函数,但有时它使用对象 MF.prototype
返回对象作为它们的原型(prototype),其他时间它返回数组。这种不一致是一个坏主意。当函数设计为通过 new
调用时(例如,它是一个构造函数),正常情况是它不返回任何内容; new FunctionName
的结果表达式将是通过 new
创建的对象。但如果构造函数返回一个非 null
对象(例如当您返回数组时),它会覆盖 new
的正常结果表达。
关于Javascript 模块模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20347326/