The default function for an object?

Is it possible to set a default function for an object so that when myObj() is called, this 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 would like to replace test.call() with just test() . Is it possible?

+7
source share
2 answers

returns 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 function being returned (right?) or window, you 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(); } } 
+6
source

Fine!

However, the problem is that the returned object is not "func". He does not have his own prototype, if any. It looks, however, easy to add:

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

See also: proto and prototype

0
source

All Articles