ShaggyInjun
ShaggyInjun

Reputation: 2963

What is this JavaScript Function.call method doing?

var function1 = function(){};
var function2 = function(){};

function1.call(function2.prototype);

I have spent way too much time trying to understand the above piece of code. Could any one explain how are function1 and function2 changed in the case above ?

functional mixins

I am able to call methods in function1 on an object of function2. So, my conclusion was function must have changed.

Upvotes: 0

Views: 108

Answers (2)

the system
the system

Reputation: 9336

Given your code example, the value of this in that invocation of function1 will be set to the value of the function2.prototype object.

var function1 = function(){
    console.log(this === function2.prototype); // true
};
var function2 = function(){};


function1.call(function2.prototype);

So methods (or other values) on function2.prototype will be accessible from this inside function1.

But if they're simply invoked as like this:

this.someMethod();

then the value of this inside the method will be the actual prototype object. This would be an unusual use.


The code example from your link seems to be this:

var asCircle = function() {
  this.area = function() {
    return Math.PI * this.radius * this.radius;
  };
  this.grow = function() {
    this.radius++;
  };
  this.shrink = function() {
    this.radius--;
  };
  return this;
};

var Circle = function(radius) {
    this.radius = radius;
};
asCircle.call(Circle.prototype);

var circle1 = new Circle(5);
circle1.area(); //78.54

In this example, the asCircle function adds methods to whatever is provided as its this value. So basically, Circle.prototype is being enhanced with additional methods as a result of this invocation.

As you can see, the .area() method becomes available in the prototype chain of Circle after it was assigned via that invocation.

So it's not that the function being invoked is using the methods, but just the opposite... it's providing new methods.

Upvotes: 5

Nicolas Straub
Nicolas Straub

Reputation: 3411

they aren't. your code is calling function1 using function2's prototype as the context. So in the call, "this" will map to function2's prototype, instead of the window object (assuming you're calling it from a browser)

Upvotes: 2

Related Questions