1

I'm trying to execute a method that's inside an object when you click a button, but apparently, it doesn't run. What am I doing wrong? I saw the variable "price" on Chrome's console, and it says "undefined" before and after pressing the button.

Javascript code:

function Upgrade () {
    this.buy = function(){
        this.price = 40;
    };
}

var upg = new Upgrade();

var button = document.getElementById("button");

button.onclick = upg.buy;

HTML code:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <div>TODO write content</div>
        <button id="button" type="button">Upgrade 1</button>
    <script src='newjavascript.js'></script>
    </body>
</html>

2 Answers 2

2

This happens because as you are assigning your method directly to the onclick property, it will be fired with this being the DOM element.

You can make it work wrapping it into an anonymous function, so the this keyword will point to your own object.

button.onclick = function() {
    upg.buy();
}

Also, I suggest you to move your method to the prototype of your function.

function Upgrade () {
    this.price = 0;
}

Upgrade.prototype.buy = function() {
    this.price = 40;
}

Assigning it to prototype will make this method shared between all objects of your function, instead of creating a new copy for each one.

Fiddle: http://jsfiddle.net/prVD9/

You can learn more about the this keyword behavior in this question: How does "this" keyword work within a function?

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

Comments

1

When you assign function to object property, this refers to new object (button in your example).

Use this code instead:

function Upgrade () {
    var that = this;
    this.buy = function(){
        that.price = 40;
    };
}

or:

button.onclick = upg.buy.bind(upg);

I recommend to read MDN - this keyword.

Comments

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.