theJava
theJava

Reputation: 15044

Context in javascript

function katana(){
  this.isSharp = true;
}
katana();
assert( isSharp === true, "A global object now exists with that name and value." );

var shuriken = {
  toss: function(){
    this.isSharp = true;
  }
};
shuriken.toss();
assert( shuriken.isSharp === true, "When it's an object property, the value is set within the object." );

I am actually not getting what is this code trying to tell?. Can anyone explain me what is Context in JavaScript and what exactly does context represent here in the above code?

Upvotes: 3

Views: 128

Answers (2)

David G
David G

Reputation: 96875

Well, the reason this === window in the first example and this === shuriken in the second example all has to do with where those functions are created. Notice that when you define shuirken.toss outside of the object, this points to the window object. And when you call katana with new, this points to the newly created object.

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173662

The first call is equivalent to:

katana.call(window); // window is now referenced as this inside the function

In a similar fashion, you could change the call to katana() like this to change the context:

var shuriken = {}
katana.call(shuriken); // shuriken.isSharp === true

The second invocation implicitly has this equivalent function call:

shuriken.toss.call(shuriken);

Upvotes: 3

Related Questions