首页 > 解决方案 > 如何在 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);

我希望现在更清楚了。

标签: javascriptcallbindapply

解决方案


当你 时.call(obj),你开始你的函数this等于那个对象。当你说 时this.id = "",你正在覆盖id你已经拥有的。

这可能是您的问题的解决方案:

if (!this.id) {
  this.id = "";
}
if (!this.property) {
  this.property = "default";
}
// etc.

推荐阅读