Mina Gabriel
Mina Gabriel

Reputation: 25070

Calling method of object

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?

jsFiddle

Upvotes: 0

Views: 66

Answers (5)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

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();​

Upvotes: 0

bokonic
bokonic

Reputation: 1771

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){ ...}
    }
};

Upvotes: 1

bobwienholt
bobwienholt

Reputation: 17610

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');​

Upvotes: 1

Dmitry Osinovskiy
Dmitry Osinovskiy

Reputation: 10118

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.

Upvotes: 0

Joseph
Joseph

Reputation: 119827

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')

Upvotes: 5

Related Questions