如何将参数传递给 JS ES6 Class 中的函数?
How to pass arguments to a function in a JS ES6 Class?
我正在尝试创建一些 ES6 classes 来清除我的 javascript 代码。我不确定如何将参数传递给 Class.
中的函数
据我所知,正确的方法是通过构造函数,但这意味着当我实例化 class.
时它们被绑定一次
在下面的示例中,我想将一个元素 elem
传递给我的函数 Categories.addCategory
。
class Categories {
constructor(id, name) {
this.id = id;
this.name = name;
}
getName() {
return this.name;
}
getId() {
return this.id;
}
addCategory(elem) {
$(elem).addClass('category');
}
}
Cat = new Categories(1, 'new products');
Cat.addCategory('#product1');
我也想知道是否有另一种方法来传递参数而不是仅使用构造函数。
抱歉,如果问题不清楚,我是 ES6 的新手 Classes,可能错过了一些核心要点。
看来您已经知道如何从 class 创建实例。现在您只需要从实例调用方法,将参数作为值传递给调用的括号。
const instanceOfCategories = new Categories('12345', 'John')
instanceOfCategories.action('.your-selector')
您可以有多个参数,传递它们的顺序就是它们到达方法的顺序。
let categories = new Categories();
categories.id = 5;
categories.name = "Books";
我正在尝试创建一些 ES6 classes 来清除我的 javascript 代码。我不确定如何将参数传递给 Class.
中的函数据我所知,正确的方法是通过构造函数,但这意味着当我实例化 class.
时它们被绑定一次在下面的示例中,我想将一个元素 elem
传递给我的函数 Categories.addCategory
。
class Categories {
constructor(id, name) {
this.id = id;
this.name = name;
}
getName() {
return this.name;
}
getId() {
return this.id;
}
addCategory(elem) {
$(elem).addClass('category');
}
}
Cat = new Categories(1, 'new products');
Cat.addCategory('#product1');
我也想知道是否有另一种方法来传递参数而不是仅使用构造函数。
抱歉,如果问题不清楚,我是 ES6 的新手 Classes,可能错过了一些核心要点。
看来您已经知道如何从 class 创建实例。现在您只需要从实例调用方法,将参数作为值传递给调用的括号。
const instanceOfCategories = new Categories('12345', 'John')
instanceOfCategories.action('.your-selector')
您可以有多个参数,传递它们的顺序就是它们到达方法的顺序。
let categories = new Categories();
categories.id = 5;
categories.name = "Books";