how to add an item to the method of an object in javascript

Multi tool use


how to add an item to the method of an object in javascript
I want to add bar
into the items
array.
bar
items
let myObj = {
item:_ => ['foo']
}
Tried doing this:
myObj.item().push('bar')
but when i do console.log(myObj.item())
i get back ['foo']
Any reasons for this behaviour ?
console.log(myObj.item())
['foo']
['foo']
if you want an array then just write
let myObj = {item:['foo']}
, no need for a method to add an array as property.– mpm
3 mins ago
let myObj = {item:['foo']}
Any reason for using
item:_ => ['foo']
instead of item: ['foo']
? Seems like you have an XY problem here.– Roko C. Buljan
1 min ago
item:_ => ['foo']
item: ['foo']
1 Answer
1
let myObj = {
item: _ => ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}
myObj.item().push('bar')
actually pushes bar to the array returned by the function myObj.item()
. But this is not persisted. Next time you call myObj.item()
you would still get ['foo'] since that is what the function returns.
myObj.item().push('bar')
myObj.item()
myObj.item()
If you want to push directly to item array, create item as an array with initial value ['foo'] like so.
let myObj = {
item: ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}
Then you can do myObj.item.push('bar');
myObj.item.push('bar');
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Yeah, it is how it works. Your function returns
['foo']
, each time you call it. Because you implemented it this way.– sjahan
6 mins ago