Josh Mackey
Josh Mackey

Reputation: 243

How to create an object in which the object itself is a function?

I have a javascript object from which I created from a constructor.

var obj = new Obj();

It has several functions but I wish to also use it as follows;

obj();

Obj is defined as:

function obj() {
   this.blah = function () {
   };
}

How can I do this?

Upvotes: 1

Views: 289

Answers (3)

Chintan
Chintan

Reputation: 372

I think you are looking for 'closure' here. Try:

function MyObject(/* constructor params */) {
   //assign properties to 'this'
   return function() {
      return this;  //<== placeholder implementation
   }.bind(this);
}
var obj1 = new MyObject();

Now if you do console.log(obj1) you will see function() { [...] } and you will be able to do obj1() to execute your function.

As a bonus in the code above, I also added this binding in the 'closure' as you will need it in most cases that you are doing anything interesting.

Upvotes: 0

Chris Bouchard
Chris Bouchard

Reputation: 805

You can create properties on function objects. For instance, if you have the function

function foo() {
    return "bar";
}

You can set a property on foo.

foo.baz = 42;

So now you can call foo and get the result "bar", and you can access its baz property.

Upvotes: 1

Travis J
Travis J

Reputation: 82267

It would be easier to have a function you call which returns an arbitrary function that is treated as both an object and a function. Each one would be unique, and you would not need to use new.

function Obj() {
 var ret = function(){
  console.log('Hello');
 };
 ret.blah = function () {
   console.log('World');
 };
 return ret;
}

var obj = Obj();

obj();//Hello
obj.blah();//World

Upvotes: 4

Related Questions