Default function on an object?

☆樱花仙子☆ 提交于 2019-12-31 22:36:06

问题


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?


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/10535447/default-function-on-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!