0

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

5
  • "I thought I could use object literals but doesn't work with functions" In what way? Using functions in object literals is incredibly common. It works just fine. Commented Oct 22, 2020 at 15:36
  • 1
    Why not? button.onClick = function() { alert('You bought House') } Commented Oct 22, 2020 at 15:36
  • 1
    If your goal is to have the message show the value of the name property, use that property rather than a hardcoded value: alert("You bought a " + button.name). Commented Oct 22, 2020 at 15:36
  • @Christiaan thanks, can you tell me why this won't work? button.onClick(() => alert('You bought House')) Commented Oct 22, 2020 at 15:46
  • Because you are calling the onClick function with a different function as argument. This is actually called a callback function. Commented Oct 23, 2020 at 7:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

without changing the actual object itself
button.onClick = function() { alert('You bought House') } That works but could you tell me why this won't button.onClick(() => alert('You bought House')) ?
In the second, you're invoking it and passing a parameter which is a function, rather than reassigning the onClick property. It'd work if you did button.onClick = () => alert('You bought House');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.