frogatto
frogatto

Reputation: 29285

Create function/object in javascript

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?

Upvotes: 2

Views: 113

Answers (2)

sanchez
sanchez

Reputation: 4530

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

Upvotes: 2

antyrat
antyrat

Reputation: 27765

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";
 }

Upvotes: 2

Related Questions