Javascript Object Methods
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();
source to share
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!
source to share