2

How I can create a thing which is both function and object at a same time?
Suppose its name is obj.
In the following context it is a object:

obj.key1 = "abc";
obj.key2 = "xyz";

And in another context it is a function like this:

var test = obj("abc");

How I can create this object in JavaScript?

2
  • 4
    This is just how functions are. Functions ARE objects. so if you do function test(param) { alert(param); }, you could do test.prop = 'testProp' Commented Aug 1, 2013 at 11:12
  • See a tutorial like net.tutsplus.com/tutorials/javascript-ajax/… Commented Aug 1, 2013 at 11:18

2 Answers 2

2
function obj( param ){
    var that = this;

    that.key1 = "default";
    that.key2 = "default";

    that.someMethod = function(){
        return param;
    };

    that.showMessage = function(){
        alert( param );
    };

    return that;
}

and then:

var test = obj("hi there");
test.key1 = "abc";
test.key2 = "xyz";
test.showMessage();

FIDDLE: http://jsfiddle.net/Xnye5/

or

obj("hi there again").showMessage();

FIDDLE: http://jsfiddle.net/Xnye5/1

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

4 Comments

Thanks for your response, can you tell me how i can implement obj("hi there").showMessage() / firebug give me error : obj is not a function
no no, i want to use this method with this convention: obj("hi there").showMessage()
I want to use my object like jQuery object
@ABFORCE you can't use it this way because obj("hi there") will return what this function return (or undefined in case of it doesnt return anything) and that returned value dont have .showMessage() method.
2

Like this:

 function obj( param ) {
     console.log( param );
 }

 obj.prototype.key1 = "abc";
 obj.prototype.key2 = "xyz"; 

 var test = new obj( "abc" );
 console.log( test.key1 );
 console.log( test.key2 );

Key new needed to save function context. You can use return this in function to avoid this.

Or using this instead of prototype:

 function obj( param ) {
     console.log( param );
     this.key1 = "abc";
     this.key2 = "xyz";
 }

1 Comment

Or var obj = function(param) {....}, just so one knows there are options, and in case he needs more than 1 of them.

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.