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>
4

2 回答 2

2

发生这种情况是因为当您将方法直接分配给onclick属性时,它将this作为 DOM 元素被触发。

您可以将其包装到匿名函数中,这样this关键字将指向您自己的对象。

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

另外,我建议您将方法移至函数的原型。

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

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

将其分配给原型将使此方法在函数的所有对象之间共享,而不是为每个对象创建一个新副本。

小提琴:http: //jsfiddle.net/prVD9/

您可以在此问题中了解有关this关键字行为的更多信息:“this”关键字如何在函数中工作?

于 2013-11-02T00:18:03.273 回答
1

当您将函数分配给对象属性时,this指的是新对象(button在您的示例中)。

请改用此代码:

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

或者:

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

我推荐阅读 MDN- this 关键字

于 2013-11-02T00:17:23.727 回答