如何创建简单的JavaScript" class"?

时间:2015-02-26 14:21:06

标签: javascript

我试图创建一个简单的JS类,然后尝试创建一个对象,但是在标记的行中它表示"无法读取属性' show'未定义"。

function DashboardNumberItem(dashboardItemId, dataUrl) {
    this.dashBoardItem = $("#" + dashboardItemId);
    this.dataurl = dataUrl;
    this.placeholder = $("#" + dashboardItemId + " .number-placeholder");
    this.dashBoardItem.hide();
}

DashboardNumberItem.prototype.loadData = function() {
    $.ajax({
        url: this.dataurl,
        method: 'GET',
        dataType: 'json',
        success : function(data) {
            this.dashBoardItem.show(); // this.dashBoardItem is undefined?!
            this.placeholder.text(data);
        }
    });
};

var dashboardItem = new DashboardNumberItem("dashboard-item-vardhandelseimportcount", "/Controller/Action");
dashboardItem.loadData();

为什么会发生这种情况?如何才能使其发挥作用?

1 个答案:

答案 0 :(得分:2)

this可能不是您期望的那样,并且将指向 jQuery的XMLHttpRequest对象而不是您的DashboardNumberItem实例,所以设置一个新变量,例如var that = this;

DashboardNumberItem.prototype.loadData = function() {
    var that = this; // set up a reference to capture it
    $.ajax({
        url: that.dataurl,
        method: 'GET',
        dataType: 'json',
        success : function(data) {
            that.dashBoardItem.show(); // which you can now use in another context
            that.placeholder.text(data);
        }
    });
};