javascript extender (TypeExtend) [ 1112 views ]
I have read on many pages that this is evil like eval. Everything is evil if you can’t use that.
Unsafe extend. In this sample I aggree with the evli idea. This is simple and dangerous.
String.prototype.Contains = function(s) {
return !!~this.indexOf(s);
};
Safe version. Better but not the best.
the skeleton
if (!TYPE.prototype.EXTENDER_FUNCTION) {
Object.defineProperty(TYPE.prototype, 'EXTENDER_FUNCTION', {
enumerable: false,
configurable: false,
writable: false,
value: THE_FUNCTION
});
};
and the code
if (!String.prototype.Contains) {
Object.defineProperty(String.prototype, 'Contains', {
enumerable: false,
configurable: false,
writable: false,
value: function (s) {
return !!~this.indexOf(s);
}
});
};
instead of this almost nice solution do the following. Write an universal function which can create the extender with some additional safe methods like:
function TypeExtend(TYPE, EXTENDER_FUNCTION, FUNCTION,
_enumerable, _configurable, _writable){
if (!TYPE['prototype'][EXTENDER_FUNCTION]) {
Object.defineProperty(TYPE.prototype, EXTENDER_FUNCTION, {
enumerable: _enumerable,
configurable: _configurable,
writable: _writable,
value: FUNCTION
});
return true;
};
return false;
};
TypeExtend(String, 'Contains', function(s) { return !!~this.indexOf(s); });
for object extending
function ObjectExtend(OBJECT, EXTENDER_FUNCTION, FUNCTION){
if (!OBJECT[EXTENDER_FUNCTION]) {
OBJECT[EXTENDER_FUNCTION] = FUNCTION;
return true;
};
return false;
};
ObjectExtend(Math, 'randomBetween',
function(min, max) { return Math.random() * (max - min) + min; }
);


