AndreaNobili AndreaNobili - 1 year ago 59
Javascript Question

How exactly work the this keyword declared into a function defined inside an object?

I am pretty new in OO paradigm in JavaScript language (I came from Java) and I have the following doubt related to the correct meaning of this param in this specific case.

I have the following code:

var obj = {

fn:function(a,b) {


Ok, from what I have understand (correct me if I am doing wrong assertion) the previous code define an ob object that contain a fnction named fn.

First doubt: doing in this way am I creating an instance of this object (creating in memory) or am I only declaring it (as a Java class)?

I think that I am creating in memory a specific instance of this object but I am not sure of this...

Ok, then doing:


here the this value is the identification of the specific obj object (the instance) on which I am calling the fn() function.

Is it my reasoning correct or am I missing something?

And what happens if I don't declare the fn() function into an object definition? What happens if I put it dirctly into a .js file? Is this keyword refred to the global object?

Answer Source

First doubt : Yes, you are creating an object in memory

There are 3 rules for determining the value of the this keyword and all of them are determined based on the callsite where a function is invoked.

1) Default binding : By default, this binds to the global object.

var a = 10; // declared in global scope

function foo(){
 console.log(this.a); // 10

foo(); // callsite 

2) Implicit binding : this binds to the object whose method is invoked

var a = 10; // global

var obj = {
  a : 20,
  foo : function(){
         console.log(this.a); // 20
  }; // callsite

3) Explicit binding : this binds to whatever object you specify. There are 2 ways to do this, call() and apply()

var a = 10;

var obj = {
   a : 20

function foo(){
   console.log(this.a); // 20
};; // bind to obj
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download