Reputation: 3361
I've created a JavaScript class that gets a reference to a function as its constructor argument. This class has an init() function which calls the init() function of the referenced function which was passed to the constructor. However, this results in an error saying that this.aFunction.init() is undefined.
This is the code:
function AClass(aFunction) {
this.aFunction = aFunction;
}
AClass.prototype.init = function() {
this.aFunction.init();
}
var aClass = new AClass(function() {
return {
init: function() {
alert('success');
}
};
});
alert('Before init');
aClass.init();
I've put up a jsFiddle at: http://jsfiddle.net/sbel/8cgpH/3/
Upvotes: 0
Views: 69
Reputation: 845
var aClass = new AClass({
init: function() { alert('success'); }
});
your aFunction just a obj
Upvotes: 0
Reputation: 224904
You need to call aFunction
to get its return value. Right now what you're doing is looking for the property init
in the function object itself, which doesn't exist.
AClass.prototype.init = function() {
this.aFunction().init();
};
Upvotes: 1
Reputation: 154828
Your function returns something. The function itself doesn't have the property init
. Call the function to get the object with its property (aFunction
is not a function anymore but the object with init
instead, so your naming would be a bit amiguous): http://jsfiddle.net/8cgpH/8/.
this.aFunction = aFunction();
Upvotes: 1
Reputation: 26730
You simply forgot to execute one function, see http://jsfiddle.net/8cgpH/5/
var aClass = new AClass(function() {
return {
init: function() { alert('success'); }
};
});
That parameter you're handing to AClass is a function that will return an object that includes a method init()
once it got invoked (you forgot to do that) - in other words: you're just handing a class but not an instance of that class.
var aClass = new AClass(function() {
return {
init: function() { alert('success'); }
};
}()); // <---
Upvotes: 1