最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Default function on an object? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked May 10, 2012 at 13:51 Elliot BonnevilleElliot Bonneville 53.4k23 gold badges100 silver badges124 bronze badges 1
  • possible duplicate of Can I overload an object with a function? – Kendall Frey Commented May 10, 2012 at 14:00
Add a ment  | 

1 Answer 1

Reset to default 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();
    }
}
发布评论

评论列表(0)

  1. 暂无评论