javascript - 如何在 JS 中使用 call 或 apply 方法覆盖该对象的属性的默认值
问题描述
我已经开始学习调用、应用和绑定,现在我想使用它但有一些问题:
我有一个功能:
let addTableRow = function() {
let template = HtmlTemplatesTelephony.ks.renderTableRow;
this.id = "";
this.creationDate = "";
this.address = "";
this.numberOfUser = "";
this.accessExisting = true;
$(DOM.tableBodyContainer).append(template(this));
};
我将 this 属性声明为默认值
在这里,我使用或不使用 .call() 调用该函数:
let updateTable = function() {
let locations = userData().locations;
if(locations.length > 0) {
for(let location of locations) {
UIController.addLocation.call(location);
}
} else {
UIController.addLocation();
}
};
我的想法是使用“addTableRow”中的“this”值作为默认值,以防在没有.call() 的情况下调用该函数。当使用 .call() 调用它时,我想覆盖“this”默认值。但恰恰相反。
我知道我可以将对象作为参数传递并设置默认对象,但是还有其他方法可以使用 .call() 吗?还是 .call() 的用例错误?
感谢帮助!
***** 更新 ******
抱歉,它是用模块模式编写的,我忘了提到函数“addTableRow”在返回对象中被称为“addLoaction”。这里还有一些代码:
我的用户界面控制器:
let UIController = (function() {
let DOM = {
tableHeadContainer: $('thead'),
tableBodyContainer: $('tbody'),
inputNumberLocations: $('#numberLocations'),
inputAddress: $('.js-location-address'),
inputUser: $('.js-location-user'),
inputVpn: $('.js-location-vpn'),
btnDeleteLocation: $('.js-delete-location'),
};
let addTableRow = function() {
let template = HtmlTemplatesTelephony.ks.renderTableRow;
this.id = "";
this.creationDate = "";
this.address = "";
this.numberOfUser = "";
this.accessExisting = true;
$(DOM.tableBodyContainer).append(template(this));
};
return {
getDOM: DOM,
addLocation: addTableRow,
removeLocation: removeTableRow
}
})();
我的主控制器:
let Controller = (function(dataController, UIController) {
let updateTable = function() {
let locations = userData().locations; // locations has the same properties as in function 'addTableTow'
if(locations.length > 0) {
for(let location of locations) {
UIController.addLocation.call(location);
}
} else {
UIController.addLocation();
}
};
return {
init: function() {
setupEventListeners();
updateTable();
},
}
})(数据控制器,UIController);
我希望现在更清楚了。
解决方案
当你 时.call(obj)
,你开始你的函数this
等于那个对象。当你说 时this.id = ""
,你正在覆盖id
你已经拥有的。
这可能是您的问题的解决方案:
if (!this.id) {
this.id = "";
}
if (!this.property) {
this.property = "default";
}
// etc.
推荐阅读
- javascript - 即使在等待网页加载时也未捕获类型错误
- mysql - 将多个值插入一列,仅在其他列中插入一个 MySql Mamp
- laravel-5 - Laravel - 在 Web 根目录中仅放置公共文件夹只会出现空白屏幕
- asp.net - ASP.Net 按钮不调用 Post 方法
- python - MD5 编码 HTML 给出 2 个不同的结果
- python-3.x - 如何在python中对分类数据应用多元回归
- azure - Azure 容器经常连接到 23.97.221.176:11041。这个端口是干什么用的?
- python - 将 2 个列表与元组、列表和整数合并
- c# - 如何在列表视图中的文件资源管理器中区分 FileInfo 和 DirectoryInfo
- entity-framework - 当在 CRUD 中创建时显示其他列然后是外键