Your function seems to expect an object parameter, but that is incorrect seeing how you call it with apply. When you call apply or call, the first argument to that method is used to set the this value for your function's execution context. It does not get passed as argument.
As your function references this, it is important that you set this correctly, and so the use of apply or call is the good choice.
So change:
let sayName = function (object, ...languages) {
to:
let sayName = function (...languages) {
Note that you didn't use object anyway in your function's code.
In the version where you don't call apply, but call the function directly, you do:
sayName(stacy, ...languages);
...but here the this object will not be set correctly. You should have used call to ensure that this will refer to stacy:
sayName.call(stacy, ...languages);
Check out the documentation of apply:
Syntax
function.apply(thisArg, [argsArray])
Parameters
thisArg
Optional. The value of this provided for the call to func. [...]
argsArray
Optional. An array-like object, specifying the arguments with which func should be called. [...]
Object oriented programming, a better way
Now, taking a step back you should really have defined sayName as a prototype method, and construct stacy like so:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName(...languages) {
console.log(`My name is ${this.name} and I speak ${languages.join(', ')}`);
}
}
let stacy = new Person('Stacy', 34);
let languages = ['Javascript', 'CSS', 'German','English', 'Spanish'];
stacy.sayName(...languages);
... and why not actually store the languages a person speaks as a property as well, and remove the console.log from the method, as it should be the caller who decides to where the output should be made (maybe to a file or to a HTML element):
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.languages = [];
}
speaks(...languages) {
this.languages = languages;
}
introduction() {
return `My name is ${this.name} and I speak ${this.languages.join(', ')}`;
}
}
let stacy = new Person('Stacy', 34);
stacy.speaks('Javascript', 'CSS', 'German','English', 'Spanish');
console.log(stacy.introduction());
applyis used as thethisobject assignment. It is not passed as argument to your function. All that is in the documentation ofapply. Since you referencethisin your function, just remove theobjectparameter from your function header.