Chris Clark
Chris Clark

Reputation: 397

How does the scope of 'this' change in Function.prototype.call()

I have this example code below. I may be way off base, but I always understood this in javascript to mean the owner of the function/object that is the calling object.

function hello() {
  var hello = [this.name, this.sayHello].join('');
  console.log(hello);
}

var obj = {
  name: 'Chris', 
  sayHello: ', how are you today?'
};

hello.call(obj);

My next thought was what is happening is obj is now receiving the hello() function to its prototype. So I then ran this right after the .call function.

obj.hello();

To my suprise I received a type error: hello is not a function. Can anyone shed some light as to what is happening on the backend of this .call() javascript function?

Edit Let me edit for clarity. The question I am asking is "How does the scope of 'this' change? The function hello() should not have this.name in scope. unless the function hello was added to the prototype of obj. But it clearly works. So what trickery is happening on the Javascript function side of .call() for this to work.

Upvotes: 0

Views: 49

Answers (3)

user5066707
user5066707

Reputation:

this is the object specified in hello.call. You can, by other way, define hello as method of this.

function hello() {
    this.hello = function() {
        console.log([this.name, this.sayHello].join(''));
    }
}

Upvotes: 0

castletheperson
castletheperson

Reputation: 33496

Function#call executes a function where this has been bound to the thisArg.

You can implement a similar function like this:

Function.prototype.myCall = function(thisArg) {
  thisArg.myBoundCall = this;
  thisArg.myBoundCall();
  delete thisArg.myBoundCall;
}

function hello() {
  var hello = [this.name, this.sayHello].join('');
  console.log(hello);
}

var obj = {
  name: 'Chris',
  sayHello: ', how are you today?'
};

hello.myCall(obj);

Upvotes: 2

jedifans
jedifans

Reputation: 2297

By doing hello.call(obj);, it doesn't then create a new method on your obj object named hello, to use later.

Upvotes: 1

Related Questions