I'm still learning quite a bit about the quirks of javascript.
So I have a "class", or function created like:
function Parser(){
....
}
Parser.prototype = {
init: function(){...},
parseChar: {}
}
Then, I'm adding some sub-methods of the parseChar
object to the prototype like this:
Parser.prototype.parseChar["*"] = function(){...}
Parser.prototype.parseChar["/"] = function(){...}
So how can I make the this reference inside those functions refer to the created instance of Parser
? And not the object parseChar
I've tried:
Parser.prototype.parseChar["*"] = function(){...}.bind(??)
I'm guessing that obviously won't work, since the instance doesn't even exist at this point.
I just want the this reference to refer to each respective instance, to be able to access properties of the Parser inside those prototype function.
I imagine this might require some magic in a constructor? I don't know, I just hope I don't have to radically alter this, because I really like the way functions are defined with the Parser.prototype.whatever
syntax.
Current Code
function Parser(){
var that = this;
}
Parser.prototype = {
state: {...},
parseChar: {},
init: function(){},
parse: function(fileName){
//random stuff
}
}
Parser.prototype.parseChar["*"] = function(){
console.log(that);
}
And then in another test file:
var Parser = require('./Parser.js');
var parser = new Parser();
parser.parse("Parser.js");
Btw, this is node.js ;)
Potential Solution
It looks like this solved my problem no, it didn't, though I'm still not sure it's the best solution, so I'm not going to accept it just yet.
In the constructor, I added:
//Bind prototype methods to the instance
for (key in this.parseChar){
var property = this.parseChar[key];
if(this.parseChar[key] instanceof Function){
this.parseChar[key] = this.parseChar[key].bind(this);
}
}
Now, in the prototype methods, I can add stuff like:
console.log(this.state);
And it works.
I could see foresee 1 of 2 problems with this approach. If either are correct or incorrect, please, let me know!
1) This method works, but it actually creates an instance of the function on each object. In which case, the whole attraction of minimizing redundant instantiation that comes with prototypes is gone. That would be fine though, because I won't be creating too many instances, and I like the readability of this solution.
Not the case. Each instance still calls the prototype's method
2) Every time a new instance is created, it actually binds the prototype's method to that actual instance, thus if I create multiple instances of Parser
, after the prototype method is bound to the new instance and all of its properties, then all preceeding instances will then reference the latest. And that would be bad.
Almost, except in reverse. For some reason, each successive instance references the first, not the latest created
Still looking for a solution...