When composing objects with functions, what's the proper way to pass parameters within the composition object?
For example:
// functions
const sayHi = () => {
console.log('Hi!');
};
const greetPerson = (name) => {
console.log(`Hello there, ${name}!`);
};
// "composition" objects, referring to the functions above
const hi = {
'id': 1,
'speak': sayHi
};
const greetWorld = {
'id': 2,
'speak': greetPerson('World') // how do I go about passing the function a parameter here?
};
const greetMars = {
'id': 3,
'speak': greetPerson('Mars')
};
// register and run each
const salutations = [hi, greetWorld, greetMars];
for (let salutation of salutations) {
salutation.speak();
}
The output when I run this is:
$ node sayHi.js
Hello there, World!
Hello there, Mars!
Hi!
/Users/rotarydial/sayHi.js:21
salutation.speak();
TypeError: salutation.speak is not a function
How do I handle this properly so I can pass greetPerson()
a parameter in the greet
object?
I think this may be what you're looking for:
// functions
const sayHi = () => {
console.log('Hi!');
};
const greetPerson = (name) => {
console.log(`Hello there, ${name}!`);
};
// "composition" objects, referring to the functions above
const hi = {
'id': 1,
'speak': sayHi
};
const greet = {
'id': 2,
'speak': greetPerson // pass in a reference to the function for later use.
};
// register and run each
const salutations = [hi, greet];
for (let salutation of salutations) {
salutation.speak("World!");
}
I suggest you read the MDN Working with Objects page, particularly the section Defining Methods
Here's an example from that page:
objectName.methodname = functionName;
var myObj = {
myMethod: function(params) {
// ...do something
}
// OR THIS WORKS TOO
myOtherMethod(params) {
// ...do something else
}
};
In the code, greetPerson('World'), greetPerson('Mars')
were getting executed at the time of object creation only.
const greetWorld = {
'id': 2,
'speak': greetPerson('World')
};
was getting evaluate to below after execution
const greetWorld = {
'id': 2,
'speak': undefined // as it was getting execute immediately, and function by default returns undefined if nothing explicitly returned from it.
};
Fix -
// functions const sayHi = () => { console.log('Hi!'); }; const greetPerson = (name) => { console.log(`Hello there, ${name}!`); }; // "composition" objects, referring to the functions above const hi = { 'id': 1, 'speak': sayHi }; const greetWorld = { 'id': 2, 'speak': () => greetPerson('World') // how do I go about passing the function a parameter here? }; const greetMars = { 'id': 3, 'speak': () => greetPerson('Mars') }; // register and run each const salutations = [hi, greetWorld, greetMars]; for (let salutation of salutations) { salutation.speak(); }
我能够通过将带有参数的函数声明为匿名函数来使其工作,如下所示:
'speak': () => greetPerson('World')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.