First off, jQuery or any other library are not an option for me.
I have a function that creates an object and I pass in some functions I want to use as methods for that object. However, I want some code to run first when these functions are called. The way I'm doing this now is:
The problem is when obj.init() is called, "this" isn't referring to obj any more. I have tried using the following bind function to no avail:Code:function createObject(init) { var obj = new Object(); obj.init = (function (init) { return function () { this.initialized = true; init(); } })(init); return obj; }
Probably it isn't working because I don't know where to call it. I want the scope to be obj, and I want this all done within the createObject function. Here's the full code:Code:Function.prototype.bind = function(scope) { var _function = this; return function() { return _function.apply(scope, arguments); } }
I am only now wrapping my head around these more advanced concepts so I'd appreciate any help on this.Code:<html><head> <script language="javascript"> function createObject(init) { var obj = new Object(); init.bind(obj); obj.init = (function (init) { return function () { this.initialized = true; init(); } })(init); return obj; } Function.prototype.bind = function(scope) { var _function = this; return function() { return _function.apply(scope, arguments); } } var initFunction = function() { alert(this); } var mrObject = createObject(initFunction); mrObject.init(); </script> </head><body></body></html>


Reply With Quote

Bookmarks