Last active
August 29, 2015 14:08
-
-
Save callmehiphop/32b38da56151b43122ec to your computer and use it in GitHub Desktop.
the worst idea ever!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Thing = Weird.extend({ | |
myProp: 'hello', | |
getMyProp: function () { | |
return myProp; | |
}, | |
setMyProp: function (value) { | |
myProp = value; | |
} | |
}); | |
Thing.getMyProp(); // => 'hello' | |
Thing.setMyProp('goodbye'); // => 'goodbye' | |
Thing.myProp; // => 'goodbye' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Weird = (function () { | |
function getParamNames (func) { | |
if (func.length === 0) return []; | |
var rFnArgs = /^function\s*[^(]*\(([^)]+)\)/; | |
var match = rFnArgs.exec(removeComments(func.toString())); | |
if (!match) return []; | |
return match[1].split(',').map(function (el) { | |
return el.trim(); | |
}); | |
} | |
function getFunctionBody(fn) { | |
var s = removeComments(fn.toString()); | |
return s.substring(s.indexOf('{')+1, s.lastIndexOf('}')); | |
} | |
function removeComments(str) { | |
var rComments = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; | |
return str.replace(rComments, ''); | |
} | |
function wrap (obj, func) { | |
var stuffs = getParamNames(func); | |
var body = 'with (this) {' + getFunctionBody(func) + '}'; | |
stuffs.push(body); | |
return Function.apply(null, stuffs); | |
} | |
function extend (obj) { | |
var wrapped = {}; | |
for (var i in obj) { | |
if (obj.hasOwnProperty(i)) { | |
if (typeof obj[i] === 'function') { | |
wrapped[i] = wrap(obj, obj[i]); | |
} else { | |
wrapped[i] = obj[i]; | |
} | |
} | |
} | |
return wrapped; | |
} | |
return { | |
extend: extend | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment