I have this module
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
I have to admit, javascript's object model is quite confusing for me. The error I'm getting is that it doesn't recognize MF.foreach in function MFList. I'm not quite aware of how instances work with this module pattern but I'd be really glad if someone could tell me how I can call MF.foreach inside a private function of the object? Thanks!
MF.prototype = {}; // set up any inheritanceDon't do that. The function will already have a blank object on itsprototypeproperty, that line is at best a no-op.MFto use itsforEachmethod. TryMF().foreachor attach the function to the constructor.