corazza
corazza

Reputation: 32384

How to access the instance when prototyping with constructor functions?

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?

Upvotes: 1

Views: 79

Answers (2)

uadnal
uadnal

Reputation: 11445

Use the this keyword to access any instance property or methods. this represents the instance. Since a is an instance property and prototype methods are instance methods, it is accessible in the prototype.

Bla = function() {
    this.a = 5;
};
Bla.prototype.foo = function () {
   console.log( this.a );
}

var x = new Bla;
x.foo(); // logs 5
​

However, if we add a method directly to Bla...

Bla.bar = function () {
   console.log( this.a ); // ERRORRRRR
}

Because bar is not an instance (prototype) method. In this case, it's a static method of Bla and doesn't have an instance and this refers to the function Bla.bar, in which case doesn't have a property a

Upvotes: 2

user1106925
user1106925

Reputation:

Use this to refer to the object on which the method was called...

console.log(this.a);

There are several ways the value of this can 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.

Bla = function()
{
    this.a = 5;
}


Bla.prototype.f = function(){console.log(this.a)};

var bla = new Bla();

bla.f(); //Logs 5

So you can see that since f was called as a method of the instance of Bla referenced by the bla variable, the value of this in f will be set to refer to that same object.

Upvotes: 2

Related Questions