Kingsamama
Kingsamama

Reputation: 33

how to change value of javascript function in object

How to I change the value of onClick? I thought I could use object literals but doesn't work with functions

const button = {
 name: 'Car',
 onClick: function () {
 alert('You bought a Car')
 }
}

// Make the alert to show "You bought House"

// Make the button text to show "Bike"
button.name = 'Bike'

Without amending the button object itself

Upvotes: 0

Views: 98

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371198

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();

Upvotes: 2

Related Questions