我学习ES 6并且我有疑问 - 使用get和set是可以理解的吗?
例如:
class Country {
get cities() {
return this.citiesList;
}
set cities(value) {
this.citiesList = value;
}
}
let country = new Country();
country.cities = ['Tokyo', 'London'];
console.log(country.cities);
为什么建议使用set并改为使用:
class Country {
getCities() {
return this.cities;
}
setCities(value) {
this.cities = value;
}
}
let country = new Country();
country.setCities(['Tokyo', 'London']);
console.log(country.getCities());
在第二个例子中,我可以:
我还有两个问题:
哪种方式更好:
A)按方法设置城市(cities.setCities()或cities = [])
B)在构造函数中设置城市:
class Country {
constructor (cities)
{
this.cities = cities;
}
}
上一个问题:
如果我希望列出城市数量,我会使用构造函数...
A)
class Country {
constructor (cities)
{
this.cities = cities;
this.citiesLength = cities.length;
}
test ()
{
//operations...
let op = this.citiesLength * 10;
}
}
或
B)
class Country {
constructor (cities)
{
this.cities = cities;
}
citiesLength()
{
return cities.length;
}
test ()
{
//operations...
let op = this.citiesLength() * 10;
}
}
答案 0 :(得分:0)
将在不同行之间回答。
class Country {
get cities() {
return this.citiesList;
}
set cities(value) {
this.citiesList = value;
}
}
let country = new Country();
country.cities = ['Tokyo', 'London'];
console.log(country.cities);
为什么建议使用set并改为使用:
class Country {
getCities() {
return this.cities;
}
setCities(value) {
this.cities = value;
}
}
let country = new Country();
country.setCities(['Tokyo', 'London']);
console.log(country.getCities());
R)这是语法糖,都修改了对象变量(记住在JS类中也是对象)。我更喜欢用户使用getter和setter,因为代码更少,更清晰。
在第二个例子中,我可以:
this.cities而不是this.citiesList(get / set cities从this.cities复制自己) 使用类时,它看起来更好:country.getCities()而不是country.cities。 我还有两个问题:
哪种方式更好:
A)按方法设置城市(cities.setCities()或cities = [])
B)在构造函数中设置城市:
class Country {
constructor (cities)
{
this.cities = cities;
}
}
R)当你知道你总是要设置这些属性并且从这个类创建的每个对象都有城市时,使用构造函数。
上一个问题:
如果我希望列出城市数量,我会使用构造函数...
A)
class Country {
constructor (cities)
{
this.cities = cities;
this.citiesLength = cities.length;
}
test ()
{
//operations...
let op = this.citiesLength * 10;
}
}
或
B)
class Country {
constructor (cities)
{
this.cities = cities;
}
citiesLength()
{
return cities.length;
}
test ()
{
//operations...
let op = this.citiesLength() * 10;
}
}
** R)B因为在A中,每次从阵列添加或删除城市时都需要设置citiesLenght。 **