My brain is hurting trying to do something which should be simple but, either due to a mistake on my part or something in the WZ JS environment, it is going horribly wrong.
Let's say I define a class:
Code: Select all
var Foo = function() {
// code to run on instantiation
// this == newly created object instance
this.fish = "haddock";
}
Foo.prototype.addTask = function() {
// code
}
Code: Select all
var bar = new Foo();
bar.fish; // haddock
bar.addTask(); // runs addTask
When instantiation happens, if I understand correclty, the following sequence happens:
* a new object is created, that inherits from constructor prototype (Foo.prototype in examples above)
* the constructor function is run, with "this" pointing at the new object (so code in Foo() is run, but scoped to the new object instead of Foo).
* unless the constructor function (Foo()) returns something, the new object is returned as the result of the whole "new" expression.
That's why bar is a new object, that inherits from Foo.prototype thus has an ".addTask()" method, and has an instance-level fish property with value "haddock".
So far so good. All easy stuff.
But what if I want new Foo() to return a function, instead of an object.
According to everything I know about ecmascript and javascript, I should just be able to do this:
Code: Select all
var Foo = function() {
var returnVal = function() {
// some code
}
returnVal.prototype = this.prototype; // where 'this' is the newly created object that would usually be returned
// I've also tried returnVal.prototype = Foo.prototype but results are the same either way :s
returnVal.fish = "haddock";
return returnVal;
} // scroll down this code block....
var bar = new Foo();
bar; // should be a function - and it is! good!
bar.addTask; // should be a function (proto inheritance) -- but it's not there! bad!
bar.fish; // should be a haddock - and it is! good!
But, for some reason which is totally eluding me, the proto chain is not working properly. Where is the .addTask() method gone?
I know I can just cheat and copy across all the Foo.protoytype methods, etc., but that's crufty and wasteful. I just want to plonk Foo's prototype on to returnVal because it's quicker and nicer.
But it's not working!!! AARRGGHHH!!! It's doing my nut in.
Can anyone see any obvious mistakes I'm making?