I have the following object:
var x = {
y: '33',
z: '88',
m: function() {
alert('this is the m element');
}
};
x.newObject = function() {
alert('mm');
function click(myval) {
alert('you have select the click function' + myval);
}
};
x.newObject.click('clickme'); // This is what I have tried; it's not working.
How can I call the click function of newObject?
5 Answers 5
In the way you are coding it, you can't access click function since it's within another function.
If you insist coding it this way, have a call to newObject (which is a function) return click in an object so that it can be accessible. It's usually called function call "chaining", where the previous call returns an object that the next call can then use:
x.newObject = function(){
alert('monmon') ;
return {
click : function (myval){
alert('you have select the click function' + myval) ;
}
}
}
//a call to newObject returns an object with a click function
x.newObject().click('clickme')
Comments
This worked:
var x = {
y: '33',
z: '88',
m: function() {
alert('this is the m element');
}
}
x.newObject = new function() {
return {
click: function(myval) {
alert('you have select the click function' + myval);
}
}
}
x.newObject.click('clickme');
Comments
click is scoped inside newObject, so it's not available anywhere outside of newObject. Are you trying to create an object with methods? If so, add it to the prototype:
newObject = function() { ... };
newObject.prototype = {
click: function(myval){ .. }
};
//now you can call newObject.click()
or you can have newObject return the methods you want to expose:
newObject = function(){
return {
click: function(myval){ ...}
}
};
Comments
Short answer: no way. Long answer: 'click' is treated somewhat like a local variable inside your bigger function, you cannot access local variables outside of function where they were declared. You need to assign your 'click' function to some globally accessed property or variable.
Comments
Maybe newObject shouldn't be a function, but an object. The following code works for me
var x = {
y: '33',
z: '88',
m: function() {
alert('this is the m element');
}
}
x.newObject = {
click: function(myval) {
alert('you have select the click function' + myval);
}
}
x.newObject.click();