什么是ES6类getter和setter呢? [英] what are ES6 class getter and setter actually?
问题描述
ES6类定义中实际的getter和setter方法是什么?他们是原型道具吗? for examle:
what are actually getter and setter methods in ES6 class definition? are they infact prototype props ? for examle:
class Person{
constructor(){};
get name(){
return 'jack';
}
set name(){
// ???
}
}
这是否等于Person.prototype.name ='杰克';
does this equals to Person.prototype.name = 'jack';
另一个问题,我看过使用实例的道具的setter的例子:
and another question, i ve seen examples of setters which utilizes the instance's prop like:
class Person{
constructor(){
this._name = 'jack';
};
get name(){
return this._name;
}
set name(val){
this._name = val;
}
}
我不想这样做,我想要类似的东西:
i dont wanna do this way, i want something like:
class Person{
constructor(){};
get name(){
return 'jack';
}
set name(val){
// like this
// name = val;
}
}
可以做些什么?
推荐答案
是的,可以这样做:只需删除setter / getter语法并在初始化期间向类添加属性:
Yes, it can be done: Just drop the setter/getter syntax and add a property to the class during initialization instead:
class Person{
constructor(name){
this.name = name;
}
}
必须使用的属性的getter / setter语法根据其他属性计算,例如来自给定半径
的圆圈的区域
属性:
The getter/setter syntax exists for properties that must be calculated based on other properties, like the area
property from a circle of a given radius
:
class Circle {
constructor (radius) {
this.radius = radius;
}
get area () {
return Math.PI * this.radius * this.radius;
}
set area (n) {
this.radius = Math.sqrt(n / Math.PI);
}
}
或者获取<$ c $的全名c> Person 具有 firstName
和 lastName
属性的对象。你明白了。
Or getting the full name of a Person
object with firstName
and lastName
properties. You get the idea.
这篇关于什么是ES6类getter和setter呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!