2012-05-10 12 views
7

¿Es posible establecer una función predeterminada en un objeto, de modo que cuando llamo al myObj() se ejecute esa función? Digamos que tengo el siguiente func objeto¿Función predeterminada en un objeto?

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

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

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

test.call(); 

me gustaría sustituir test.call() con simplemente test(). ¿Es eso posible?

+0

Este es un duplicado. Tratando de encontrarlo ... –

+0

@KendallFrey: ¿Ah, sí? Lo siento por eso. –

+0

posible duplicado de [¿Puedo sobrecargar un objeto con una función?] (Http://stackoverflow.com/questions/4946794/can-i-overload-an-object-with-a-function) –

Respuesta

6

retorno a una función:

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

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

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

test(); 

pero luego this se refiere a la función devuelta (? Derecha) o ventana, tendrá que almacenar en caché this para acceder a ella desde el interior de la función (this._func();)

function func(_func) { 
    var that = this; 

    this._func = _func; 

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

Sweet, that did the the truco. ¡Gracias! –

+1

Eso ayudó mucho. Solo por gritos, así es como terminé usando esto: http://jsfiddle.net/TkZ6d/9/ ¡Gracias de nuevo! –

0

Genial!

Sin embargo, el problema es que el objeto que devuelve no es un "func". No tiene su prototipo, si hay alguno. Eso se ve sin embargo fácil de añadir:

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"))

Consulte también: proto and prototype

Cuestiones relacionadas