1

I have been using/calling functions from objects like this:

var object = { 
    fn: function(){ 
        alert('i can see it!'); 
    }
}; 
object.fn(); // it works

but I don't know how to call function from mere {} object.

{
    fn: function() {
        alert('i can\'t see it');
    }
}

fn(); // wont work ?

I want to know why this is not working? Is there a way to make it work?

2
  • 2
    It's not working because you haven't given a name to the object (which is a block scope, rather than an 'object') that defines where it should 'look' to find the function. Commented Nov 30, 2013 at 16:13
  • A simple fiddle. jsfiddle.net/6LUwZ/1 Commented Nov 30, 2013 at 16:16

4 Answers 4

4

Your second example is invalid syntax. The {} is interpreted as a block statement with a label and an invalid function because it has no name.

If you wanted to do it inline like that, you'd need something more like this:

({
    fn: function() {
        alert('now i can see it');
    }
}).fn();

Now you're creating an object since the {} can no longer be a block statement, but is instead object literal syntax. Then you're immediately accessing the fn property you defined.

Of course there's little point to this, but it's closer to what you were doing.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2168042 - that's great, but as noted in the answer, doing it like this makes absolutely no sense ?
1

fn is inside the blocks and not inside the object. Passing name-value just inside blocks ie {} dont work. Or atleast give some label to the block.

Comments

0

Call it like so: object.fn();. As @BlueSkies said, the second example will not work, as it is invalid syntax. You can't do that in JavaScript. If you name that object like David said in the comments, then it will work. You can't call a function out of an anonymous object.

Here is an example with the object being called e: http://jsfiddle.net/dhF5k/

Comments

0

Here is the proper syntax to define a "standalone" function (with no wrapper object) :

var fn = function () { ... };
function fn() { ... };

1 Comment

The brackets were actually balanced properly. It's just that there was another one hiding at the end of the alert();. I edited the question... waiting for peer review.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.