I am new with Javascript. I have a javascript class with calling recursive inside. But when running I got an error :
$(...).display is not a function at $(item).display(false);
this is my code:
function ScopeData(table, parentRow) {
const tableData = table;
const scopeEl = parentRow;
var childScope = [];
var childRows = [];
this.display = function aa(isDisplay) {
childRows.each(function (index, el) {
if (isDisplay) {
$(el).removeClass("hidden");
}
else {
$(el).addClass("hidden");
}
});
if (!isDisplay) {
var display1 = this.display;
for (let i = 0; i < childScope.length; i++) {
const item = $(childScope)[i];
$(item).display(false);
}
}
}
this.findChildRow = function () {
var scope = $(scopeEl).data("scope")
childRows = $(tableData).find("tr[data-parent='" + scope + "']");
}
this.createChildScope = function () {
$(childRows).each(function (index, el) {
var scope = $(el).data("scope")
if (scope !== "" && scope !== undefined) {
var childRows = $(tableData).find("tr[data-parent='" + scope + "']");
var dataRow = new ScopeData(table, $(el));
dataRow.init();
childScope.push(dataRow);
}
});
}
this.init = function () {
var display = this.display;
this.findChildRow();
this.createChildScope();
$(scopeEl).find("i").on("click", function () {
display(false);
})
}
}
Please help me fix the issue. Thank in advance
Welcome to javascript and how this
keyword is evaluated. I highly recommend reading this before proceeding as it is one of javascript core concepts. One hacky way to solve your problem is:
Assign the this
into a variable and use that instead.
function ScopeData(table, parentRow) {
var self = this;
...
this.init = function () {
var display = self.display;
One cleaner way to do this, is binding the function which is supported by any modern browser.
this.display = function aa(isDisplay) {
childRows.each(function (index, el) {
if (isDisplay) {
$(el).removeClass("hidden");
}
else {
$(el).addClass("hidden");
}
});
if (!isDisplay) {
var display1 = this.display;
for (let i = 0; i < childScope.length; i++) {
const item = $(childScope)[i];
$(item).display(false);
}
}
}
this.display = this.display.bind(this);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.