-1

I am looking for a shorter way to make a JavaScript object that can be used as a function. For instance, I can do the following:

var A=function(){window.alert('Hello World');}
A.hello='World';

Notice that I can call A() or access A.hello.

Is there a way to accomplish this using curly braces to create the object?

var A={
    ?:function(){window.alert('Hello World');},
    hello:'World',
};
3
  • No, only functions can be used as functions (are callable). But as functions are objects as well you can easily assign properties to them. Commented Feb 15, 2012 at 1:29
  • If you just want shorter you can omit the var statement and say function A() ... with effectively the same result. But as per am not i am's answer there isn't a syntax to create a function and give it properties all in one statement. Commented Feb 15, 2012 at 1:34
  • Whats its the point? I mean if you replace ? by $ you easy could do A.$() and get the result with only two extra characters, what do you want to get? Commented Feb 15, 2012 at 1:45

3 Answers 3

3

As you know a function is an Object. Nothing prevents you from writing properties in the function itself.

function A(){
    this.width = 200;
}

A.height = 120;

If you want to access the properties written in the function from the function itself, you must use the 'callee' attribute of the 'arguments':

function A(){
    this.width = 200;
    alert(this.width +'x'+ arguments.callee.height);
}

A.height = 120;

A(); // should alert "200x120"
Sign up to request clarification or add additional context in comments.

Comments

1

"Is there a way to accomplish this using curly braces to create the object?"

No, there's no official syntax to create callable objects other than creating a Function object.

Comments

0

by the first way, A is a function, you can use it like this: A();

by the second way, A is an object

Comments

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.