Below, is a simplified version of my App, the following code works as intended. I can see 4 logs in my console with the arguments I passed to SayHello.
var App = {};
(function(that){
that.SayHello = function(){
console.log( arguments );
return {
doSomething: function(){
console.log('done');
}
};
};
var obj = {
t: new that.SayHello( 'a', 1 ),
r: new that.SayHello( 'b', 2 ),
b: new that.SayHello( 'c', 3 ),
l: new that.SayHello( 'd', 4 )
};
}(App));
issue: I am trying to create a “shortcut” to new that.SayHello as follow:
var Greet = function(){
return new that.SayHello;
},
obj = {
t: Greet( 'a', 1 ),
r: Greet( 'b', 2 ),
b: Greet( 'c', 3 ),
l: Greet( 'd', 4 )
};
The console logs 4 empty arrays. Wich means the arguments failed to pass.
I also tried return new that.SayHello.apply(this, arguments); and return new that.SayHello.call(this, arguments);.
How can I pass ALL Greet‘s arguments to that.SayHello ?
Knowing that I have to initialize that.SayHello using new that.SayHello or else my code breaks.
I am looking for a general solution for any number of arguments, I don’t want to pass the arguments one by one.
This code is also available on jsfiddle.
Something like this?
You should know that
applyappliesargumentsto objectresult. Predefiningresultas aSayHelloprototype will give you what you want.EDIT
Unfortunetly the code above will alter the prototype of
SayHello. This is obviously unwanted behaviour so to avoid this I think we should copy the prototype object. For example use the following codeI’ve found this simple version of
clonefunction in this answer. There are many problems with it and you should check other answers. For example using jQuery’s$.extend({},originalObject)might be a good idea.Note that if you don’t care about prototype chaining (although you should) you can always do something very simple like this:
If you don’t care about older browsers (ECMAScript 5) then you can use
Object.createmethod: