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:
Code:
function createObject(init)
{
var obj = new Object();
obj.init = (function (init) {
return function () {
this.initialized = true;
init();
}
})(init);
return obj;
}
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:
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:
<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>
I am only now wrapping my head around these more advanced concepts so I'd appreciate any help on this.
Let's start with the simple solution: passing function init to function createObject which attaches function init to object obj:
PHP Code:
function createObject(init) {
var obj = new Object();
obj.text = "hi ";
obj.init = init;
return obj;
}
Now, you can do this:
PHP Code:
var o = createObject(function(x) { alert(this.text + x); });
o.init("guy");
... and expect to see "hi guy" show up on your screen.
From here, we want to do something else before init() is performed, without exposing the original init(). My understanding is that "something else" needs to be performed first every time init() is called, and then the supplied init function need to be called. So, we do this:
PHP Code:
function createObject(init) {
var obj = new Object();
obj.text = "hi ";
obj.init = function(x) {
this.text = 'bye ';
init.call(this, x);
}
return obj;
}
So, when you do this:
PHP Code:
var o = createObject(function(x) { alert(this.text + x); });
o.init("guy");
Awesome, thanks. That works great and is much simpler than what I was doing. I did run into another situation where I did need to use a binding function and what I was trying to do did work there (in the callback function that ran after an ajax call).
If these forums could let us vote posts as useful, yours would definitely get my vote. Very clean solution, and very good explanation showing the steps to arrive at that solution.
Bookmarks