Javascript Object Methods

Why can't I do this?

var MyObject = {}
MyObject.foo = function(){
  this.sayhello = function(){
    alert('Hello');
  }
}
MyObject.foo.sayhello();

      

Any ideas on how this can be done?

+3


source to share


4 answers


inside foo

, this

links MyObject

, which means that after:

MyObject.foo();

      

you may call:

MyObject.sayhello();

      

If you want to call MyObject.foo.sayhello()

, you need to sayhello

be a function on MyObject.foo

:



var MyObject = {}
MyObject.foo = function () {...};
MyObject.foo.sayhello = function () {
    alert('hello');
}

      

If you don't need foo

it to be a function, you can simply declare:

var MyObject = {
    foo: {
        sayhello: function () {
            alert('Hello');
        }
    }
}

      

which will allow you to call:

MyObject.foo.sayhello();

      

+6


source


You need to call it first to actually add the MyObject.foo()

function this.sayhello

. Then you can callMyObject.foo.sayhello();



+1


source


var MyObject = {}
MyObject.foo = {
  sayhello: function(){
    alert('Hello');
  }
}
MyObject.foo.sayhello();

      

0


source


This is because the function doesn't exist yet. So first you need to call foo. What you are doing is calling the sayhello function from the foo property. But you don't have the foo property. You have a function foo.

But you can also do this and make it chaining like jQuery does:

var MyObject = {}
MyObject.foo = function(){
  this.sayhello = function(){
    alert('Hello');
  }
  return this;
}
MyObject.foo().sayhello();

      

Make a sayhello function inside a foo object so no chaining. But an object inside an object with a function.

var MyObject = {
    foo : {
        sayhello : function(){
            alert("hello");
        }
    }
}
MyObject.foo.sayhello(); // Now does work!

      

0


source







All Articles