Inside the function, refer to the current instance's name property instead of hardcoding Car:
const button = {
name: 'Car',
onClick: function() {
alert('You bought a ' + this.name);
}
};
button.onClick();
button.name = 'Bike';
button.onClick();
If the onClick is invoked on the press of an actual button in the DOM, make sure to preserve the calling context, eg:
someHTMLButtonElement.addEventListener('click', () => button.onClick());;
If you can't change the button object, I guess you could reference a standalone name variable instead:
const button = {
onClick: function() {
alert('You bought a ' + itemBought);
}
};
let itemBought = 'Car';
button.onClick();
itemBought = 'Bike';
button.onClick();
button.onClick = function() { alert('You bought House') }nameproperty, use that property rather than a hardcoded value:alert("You bought a " + button.name).onClickfunction with a different function as argument. This is actually called a callback function.