Why I cannot do this?
var MyObject = {}
MyObject.foo = function(){
this.sayhello = function(){
alert('Hello');
}
}
MyObject.foo.sayhello();
Any ideas on how it could be done?
Why I cannot do this?
var MyObject = {}
MyObject.foo = function(){
this.sayhello = function(){
alert('Hello');
}
}
MyObject.foo.sayhello();
Any ideas on how it could be done?
within foo
, this
references MyObject
, which means that after:
MyObject.foo();
you can call:
MyObject.sayhello();
If you want to be able to call MyObject.foo.sayhello()
, you need sayhello
to be a function on MyObject.foo
:
var MyObject = {}
MyObject.foo = function () {...};
MyObject.foo.sayhello = function () {
alert('hello');
}
If you don't need foo
to also be a function, you could simply declare:
var MyObject = {
foo: {
sayhello: function () {
alert('Hello');
}
}
}
which would allow you to call:
MyObject.foo.sayhello();
You have to call MyObject.foo()
first so that the this.sayhello
function actually gets added. Then you should beable to call MyObject.foo.sayhello();
var MyObject = {}
MyObject.foo = {
sayhello: function(){
alert('Hello');
}
}
MyObject.foo.sayhello();
That is because the function does not yet exist. Therefore you must call foo first. What you do is calling the function sayhello from the property foo. But you don't have a property foo. You have a function foo.
But you can also do this and make it chain, like jQuery does:
var MyObject = {}
MyObject.foo = function(){
this.sayhello = function(){
alert('Hello');
}
return this;
}
MyObject.foo().sayhello();
Make a function sayhello inside object foo, so not a chained function. But an object inside an object with a function.
var MyObject = {
foo : {
sayhello : function(){
alert("hello");
}
}
}
MyObject.foo.sayhello(); // Now does work!