I’m extending a constructor class’ functionality via the prototype method, but I’m having trouble figuring out how to access the soon-to-be instance of the constructor class.
Lets say we have the following class:
Bla = function()
{
this.a = 5;
}
Simple enough. Now, I will extend it with a very simple method…
Bla.prototype.f = function(){console.log("Abdf.")};
new Bla().f(); //Logs "Abdf as expected."
But, what if I wanted to access the a property (5)? Say I am trying to extend the constructor class like this:
Bla.prototype.f2 = function(b){return b * here_are_the_problems.a};
Apparently using this refers to something else. What should I use instead?
Use
thisto refer to the object on which the method was called…There are several ways the value of
thiscan be set. One is that it generally refers to the object on which the function was called if the function was called as a method of the object.So you can see that since
fwas called as a method of the instance ofBlareferenced by theblavariable, the value ofthisinfwill be set to refer to that same object.