2

The code goes like this

var ob = {
    a: function() {
        b()
    },
    b: function() {
        console.log("hi")
    }
};

As you can see, you can't do

ob.a() //returns error

Can someone explain the reason in depth?

1
  • Add this keyword to function call: var ob = {a:function(){this.b()},b:function(){console.log("hi")}}; Commented Aug 8, 2015 at 9:22

3 Answers 3

2

Becuase b does not exist in the current scope (which is the global one in this case).

This works, however:

var ob = {
  a: function () {
    this.b()
  },
  b: function () {
    console.log('hi')
  }
};

because this refers to the ob object.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no function b defined anywhere, it's a property of object ob, so you can refer it as this.b from inside a:

var ob = {
    a: function () {
        this.b();
    },
    b: function () {
        console.log("hi");
    }
};

ob.a();

You could also access b as ob.b().

Comments

1

The b is a property of the object called ob. That being said, if you use

ob.b

instead of b you will solve your problem.

var ob = {
    a:function(){ 
        ob.b() 
    },
    b:function(){
        console.log("hi")
    }
};

Another way to do achieve this is to use the this operator.

var ob = {
    a:function(){ 
        this.b() 
    },
    b:function(){
        console.log("hi")
    }
};

The this holds a reference to the object you define. Hence using it you can access is properties. It is a better way that the first way, because if you decide later to alter the name of ob to obj, you will not have change it in two places.

1 Comment

@jeff Thank you :). I was about to add it, when you hit your comment !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.