Ell*_*lle 7 javascript function object
是否可以在对象上设置默认函数,以便在调用myObj()
该函数时执行?假设我有以下func
对象
function func(_func) {
this._func = _func;
this.call = function() {
alert("called a function");
this._func();
}
}
var test = new func(function() {
// do something
});
test.call();
Run Code Online (Sandbox Code Playgroud)
我想test.call()
简单地替换test()
.那可能吗?
返回一个函数:
function func(_func) {
this._func = _func;
return function() {
alert("called a function");
this._func();
}
}
var test = new func(function() {
// do something
});
test();
Run Code Online (Sandbox Code Playgroud)
但是然后this
引用返回的函数(对吗?)或窗口,你必须缓存this
从函数内部访问它(this._func();
)
function func(_func) {
var that = this;
this._func = _func;
return function() {
alert("called a function");
that._func();
}
}
Run Code Online (Sandbox Code Playgroud)