Wenmo Shang
Wenmo Shang

Reputation: 13

What does the 'this' point to in prototype method?

The question confuses me for a time. Here's a simple code:

function A() {};

A.prototype.B=function() {return this};

A.prototype.B();

The result in chrome console is:

A{};
  >B: function() {};
  >constructor: function A() {};
  >  proto: Object

As I know, 'this' point to the object who called the method. So I think the 'this' in the prototype method points to the A.prototype (prototype is also an object, right?).

I'm wondering what does the 'this' point to in the prototype method. The A or A.prototype?

And what is the A{} in the result? What is the difference between it and function A()?

Upvotes: 1

Views: 94

Answers (3)

Ely
Ely

Reputation: 11162

this refers to the object that called the function.

So whatever object you create. If that object calls the function then this refers to it.

Upvotes: 0

Khalid
Khalid

Reputation: 4808

if you instanciate the constructor A like this

var myVariable = new A();

then the method B returns the instance of myVariable

myVariable.B() === myVariable // true

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074555

So I think the 'this' in the prototype method points to the 'A.prototype' (prototype is also an object, right?)

In that example, yes. But that's an extremely unusual way to call a function on a prototype. If you called it in a more typical way:

var a = new A();
a.B();

...then this would be the instance created by new A (which a refers to).

I'm wondering what does the 'this' point to in the prototype method. The A or A.prototype?

In your call, A.prototype. You could make it point to A instead, though, using Function#call or Function#apply:

A.prototype.B.call(A);

...because this, in JavaScript, is effectively a function argument and can be set when you call the function. (Except with "bound" functions [see Function#bind] or ES6's new "arrow" functions, which have a lexically-bound this.)

And what is the 'A{}' in the result?

That's just the way the console in the browser you're using represents that the object is related to the A constructor.

Upvotes: 1

Related Questions