Chris Clark Chris Clark - 3 months ago 10
Javascript Question

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.

Answer

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);