Use case is similar to "How can I use an object as a function and an object?"
My current solution:
var newObj = function(_id){
var obj = function(arg){
console.log('call', _id, arg);
}
obj.test = function(arg){
console.log('test', _id, arg);
}
console.log('new', _id);
return obj
}
var obj = newObj('1');
obj('2');
obj.test('3');
Now, this works perfectly, if you have small number of objects.
But, when you get large number of methods and a lot of objects, you'd want to move all methods to prototype. How is it possible to do?
Naive solution, like this:
var Obj = function(id){
this.id = id
console.log('new',id)
}
Obj.prototype = function(arg){
console.log('call', this.id, arg)
}
Obj.prototype.test = function(arg){
console.log('test', this.id, arg)
}
var obj = new Obj('1');
obj('2'); // this fails with "TypeError: obj is not a function"
obj.test('3');
does not work.
EDIT: End objective is to shorten syntax of the most used method of an object.
For example: bus
object has method post
. This method is called 99.99% time, when you are doing something with bus
. Always writing bus.post(...)
is redundant. Creating closures or bindings is also not an option, as there are many buses.
Current solution (without prototype) works fine though, with small number of objects.