2012-05-10 97 views
7

是否可以在對象上設置默認功能,以便在我致電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(); 

我想用簡單的test()更換test.call()。那可能嗎?

+0

這是一個重複。試圖找到它... –

+0

@肯德爾弗雷:哦,它是?對於那個很抱歉。 –

+0

可能重複的[我可以用函數重載一個對象?](http://stackoverflow.com/questions/4946794/can-i-overload-an-object-with-a-function) –

回答

6

回報功能:

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

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

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

test(); 

但隨後this返回的函數(?右)或窗口,你將不得不緩存this從訪問它的函數內部(this._func();

function func(_func) { 
    var that = this; 

    this._func = _func; 

    return function() { 
     alert("called a function"); 
     that._func(); 
    } 
} 
+0

甜,那做了招。謝謝! –

+1

這幫了很大忙。只是爲了嘶嘶聲,這是我如何使用這個結束:http://jsfiddle.net/TkZ6d/9/再次感謝! –

0

太棒了!

但問題是,你返回的對象不是一個「func」。它沒有它的原型,如果有的話。這看起來不過容易添加:

func = function (__func) 
 
{ 
 
    var that = function() 
 
    { 
 
    return that.default.apply(that, arguments) 
 
    } 
 
    that.__proto__ = this.__proto__ 
 
    if (__func) 
 
    that.default = __func 
 

 
    return that 
 
} 
 

 
func.prototype = { 
 
    serial: 0, 
 
    default: function (a) { return (this.serial++) + ": " + a} 
 
} 
 

 
f = new func() 
 
f.serial = 10 
 
alert(f("hello")) 
 

 
f = new func(function (a) { return "no serial: " + a }) 
 
alert(f("hello"))

參見:proto and prototype