I have an instance of a logging class “logger”, this class has a function “log(txt)”, which works.
Now I am declaring a different class “Runner” and I pass it the logger instance in the constructor. Everything works until line 5, but line 7 does not write to the log:
var Runner = function (logger) {
// constructor:
logger.log("this way it works");
this.logger = logger; //line 4
this.logger.log("this also works"); //line 5
this.logf = this.logger.log; //create a shorthand for logging
this.logf("this is not written to log. why? i thought i can create a var for a function"); //line 7
};
var logger = new Logger(); //class not shown here
var runner = new Runner(logger);
var otherinstancce = new OtherClass(logger) //line 12
Can you explain what is my mistake?
unlike some other languages, “this” in javascript is dynamic, that is, “this” is the context in which the function was called, not where is was defined.
to create coupling between function and its context you have to “lock” the context in a closure. Most frameworks provide a sugar for this in form of bind() method, which, in simplified form, looks like this
with locked context function assignment works as expected