[英]Javascript nested dictionary null values
下面,我在JS中聲明了一個“類”,並為此編寫了方法。 該類表示一個小部件( 更多信息類結構 )。
我遇到的問題是,當我在setAttr ibutes方法中打印“ this”時,輸出為:
當我在下一行打印“ this.opts”時:
注意 :在擴展之前,“狀態”和“功率”的值在第二個輸出中顯示為“空”。 這可能是嘗試打印'this.opts.status'時獲得'null'的唯一可能原因。
碼
function PowerStatus(options) {
this.opts = {
meterName: '-',
displayName: null,
status: null,
power: null,
mainDiv: null,
};
this.opts = $.extend(this.opts, options);
this.opts.mainDiv = '#' + this.opts.mainDiv;
this.onClick = function () {
console.log('Clicked ' + this.opts.meterName);
};
// fill in missing attributes
this.getAttributes();
this.setHtml();
this.bindUIActions();
}
PowerStatus.prototype.getAttributes = function () {
var _this = this;
if (this.opts.displayName == null) {
getDisplayName(function (dName) {
_this.opts.displayName = dName;
}, _this.opts.meterName);
}
if (_this.opts.status == null || _this.opts.power == null) {
_this.getStatus(function (status, power) {
_this.opts.status = status;
_this.opts.power = power;
}, _this.opts.meterName)
}
};
PowerStatus.prototype.setHtml = function () {
var _this = this;
var divType = this.opts.mainDiv.split('-').slice(1).slice(0, -1).join('_');
var url = '/static/' + divType + '/html/' + divType + '.html';
$(this.opts.mainDiv).load(url, function () {
_this.setAttributes();
});
};
PowerStatus.prototype.setAttributes = function () {
var div = $(this.opts.mainDiv).find('.load-name');
var span = $('span:first', div);
span.text(this.opts.displayName);
div = $(this.opts.mainDiv).find('.load-value');
span = $('span:first', div);
span.text(this.opts.power);
};
PowerStatus.prototype.bindUIActions = function () {
var _this = this;
$(this.opts.mainDiv).on('click', function () {
_this.onClick();
});
};
PowerStatus.prototype.getStatus = function (callback) {
$.ajax({
method: "GET",
dataType: "json",
url: "/widget/power_status/status/",
data: {name: this.opts.meterName},
success: function (data) {
if (typeof callback === "function") callback(data.status, data.power);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
};
點擊處理程序內的this
值與this
處理程序外的值不同。 您需要藏匿this
在一個局部變量並使用它。
var statusObj = this;
this.onClick = function () {
console.log('Clicked ' + statusObj.opts.meterName);
};
或者,您可以使用.bind()
:
this.onClick = function () {
console.log('Clicked ' + this.opts.meterName);
}.bind(this);
始終根據調用的情況在每次對函數的調用上設置this
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.