简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM