Created
July 18, 2013 06:07
-
-
Save goodwillcoding/6027031 to your computer and use it in GitHub Desktop.
wrapping javascript function calls on an object to pass in object instance as first argument "self"
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
<html> | |
<script> | |
// ......................................................................... // | |
/* | |
* Function to wrap every method in the function to have self | |
*/ | |
function selfify (obj) { | |
// go over each property in the given object | |
for (var prop in obj) { | |
// if the object is not inherited and is a funciton | |
if (obj.hasOwnProperty(prop) && typeof obj[prop] === "function") { | |
// wrap it in a function that passes in this obj as self | |
(function (old_method) { | |
obj[prop] = function () { | |
// call the object and return the given "obj" | |
return old_method.apply( | |
obj, | |
[obj].concat(toArray(arguments)) | |
); | |
}; | |
}(obj[prop])); | |
} | |
} | |
// 4 | |
function toArray (thing) { | |
return Array.prototype.slice.call(thing); | |
} | |
return obj; | |
} | |
var TestClass = function () { | |
return { | |
zzz: {}, | |
foo: function foo (self, test_inst) { | |
var elem = document.getElementById('test_button'); | |
elem.addEventListener('click', | |
function () { | |
self.bar(test_inst); | |
} | |
) | |
}, | |
bar: function bar (self, test_inst) { | |
console.log("self:", self); | |
console.log("test_inst:", test_inst); | |
console.log(self === test_inst) | |
} | |
}}; | |
</script> | |
<input id="test_button" type="button" value="test" /> | |
<script> | |
var inst = selfify(TestClass()); | |
inst.foo(inst); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment