I am new to javascript and I’m trying some different things.
Take this following example:
function obj(){
this.execute = function(codeToExecute){
codeToExecute();
}
}
// Object init and function call
var obj = obj();
obj.execute(function(){
alert("G'Day!");
}
This will execute the alert message. All good until now but now I’m trying to alert a message transmitted through a parameter:
var obj = obj();
obj.execute(function(message){
alert(message);
}
What should be the structure of the function obj() now that I have to insert that parameter somewhere?
I couldn’t find anything useful on google because honestly I don’t know exactly what I should be looking for. Thank you!
You can extend
executeso that any additional parameters are passed to the supplied function:This line is the “magic” one:
It uses the
Array.prototype.slicefunction which is used to copy arrays, but (kind of) tricks the function into using theargumentspseudo-array as the source array (instead of the supplied[]), copying all of the elements apart from the first.You can’t just use
arguments.slice(1)becauseargumentsisn’t a real JS array. It has a.lengthproperty, and you can accessarguments[n], but it doesn’t have all of the extra functions in itsprototypethat a real array has. It’s close enough though that the implementation of.slice()doesn’t know any better.NB: you should use
newto create an object instance – in your original code you’re just callingobj()immediately and then reassigning the (undefined) result back toobj– that code could never have worked at all.