类中的 JS 吸气剂和吸气剂? [英] JS getters and setters inside a class?
本文介绍了类中的 JS 吸气剂和吸气剂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 JS 中创建一个使用本机 getter 和 setter 的类.我知道我可以为对象创建 getter/setter,如下所示:
I'd like to create a class in JS that uses native getters and setters. I know I can create getters/setters for objects, like so:
var obj = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
}
我也知道我可以在类/函数中使用 this.__defineGetter__
,但 MDN 表示不鼓励使用 __defineGetter__()
等.
I also know that I can use this.__defineGetter__
inside a class/function, but MDN says that using __defineGetter__()
etc is discauraged.
是否有比以下更好的方法将 getter 和 setter 添加到 js 类:
Is there any better way to add getters and setters to js class than:
function class(){
};
class.prototype = {
get value(){
//....
}
?
推荐答案
2019:ES6 万岁!
2019: Hooray for ES6!
class Person {
get name() {
return this._name + '!!!'
}
set name(newValue) {
this._name = newValue
}
constructor(name) {
this._name = name
}
}
const me = new Person('Zach')
console.log(me.name) // Zach!!!
me.name = 'Jacob'
console.log(me.name) // Jacob!!!
// Of course, _name is not actually private.
console.log(me._name) // Jacob
这篇关于类中的 JS 吸气剂和吸气剂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文