I'm going to assume that fatRabbit
is meant to be whiteRabbit
and that your question is why you only see Burp!
instead of the full array.
The reason is that apply
uses the array to call your function with discrete arguments, so the first entry shows up as the line
parameter, and you're not seeing the others because you don't have parameters for them.
If you want to see the array, use call
rather than apply
; then line
will refer to the array, not just the first entry:
function speak(line) {
console.log(line);
}
var whiteRabbit = {type: "white", speak: speak};
speak.call(whiteRabbit, ["Burp!","Skree","Hello"]);
Alternately, add more parameters in the method (speak(line1, line2, line3)
).
In a comment, you've asked:
Can you show how to make it dynamic?
If by "dynamic" you mean it logs as many entries as it gets, I'd use call
(as above) and a loop:
function speak(lines) {
lines.forEach(function(line) {
console.log(line);
});
}
var whiteRabbit = {type: "white", speak: speak};
speak.call(whiteRabbit, ["Burp!","Skree","Hello"]);
That's using forEach
, but you have lots of other options.