7

Is it possible to set a default function on an object, such that when I call myObj() that function is executed? Let's say I have the following func object

function func(_func) {
    this._func = _func;

    this.call = function() {
        alert("called a function");
        this._func();
    }
}

var test = new func(function() {
    // do something
});

test.call();

​I'd like to replace test.call() with simply test(). Is that possible?

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • possible duplicate of [Can I overload an object with a function?](http://stackoverflow.com/questions/4946794/can-i-overload-an-object-with-a-function) – Kendall Frey May 10 '12 at 14:00

1 Answers1

7

return a function:

function func(_func) {
    this._func = _func;

    return function() {
        alert("called a function");
        this._func();
    }
}

var test = new func(function() {
    // do something
});

test();

but then this refers to the returned function (right?) or window, you will have to cache this to access it from inside the function (this._func();)

function func(_func) {
    var that = this;

    this._func = _func;

    return function() {
        alert("called a function");
        that._func();
    }
}
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123