对象的默认功能? [英] Default function on an object?

查看:92
本文介绍了对象的默认功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在一个对象上设置一个默认函数,例如当我调用 myObj()时,该函数被执行?让我们说我有以下 func object

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

我想要替换 test.call(),只需 test()

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

推荐答案

返回一个函数:

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

但是这个指的是 return function(right?)or window ,您必须缓存 this 才能从函数内部访问它( this._func ();

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

这篇关于对象的默认功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆