有没有办法在 JS 函数 class 中使用 属性 获取和设置符号?
Is there a way to use property get and set notation in a JS function class?
JavaScript 的构造函数中有没有办法对属性使用 getter 和 setter 语法?
这是我的所需语法的示例:
function DemoClass()
{
var mFooProperty = 0;
get FooProperty()
{
return mFooProperty;
}
set FooProperty(value)
{
mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
您可以在 Javascript 中使用 class 并将属性设置为 class 实例,然后使用 getters/setters like
class DemoClass {
constructor() {
this.mFooProperty = 0;
}
get FooProperty() {
return this.mFooProperty;
}
set FooProperty(value) {
this.mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
The bodies of class declarations and class expressions are executed in
strict mode
i.e. constructor, static and prototype methods,
getter and setter functions are executed in strict mode.
为了将 属性 的实际存储保留为私有变量,您必须使用对象 API 来定义 getter 和 setter 在构造函数中:
function DemoClass() {
var mFooProperty = 0;
Object.defineProperties(this, {
fooProperty: {
get: function() { return mFooProperty; },
set: function(value) { mFooProperty = value; }
}
});
}
现在当您构造一个实例时,该实例将显示为有一个名为 "fooProperty" 的 属性。引用 属性 的值将调用 "getter" 函数,设置该值将调用 "setter":
var d = new DemoClass();
console.log(d.fooProperty); // calls getter 0
d.fooProperty = 3; // calls setter
console.log(d.fooProperty); // 3
JavaScript 的构造函数中有没有办法对属性使用 getter 和 setter 语法?
这是我的所需语法的示例:
function DemoClass()
{
var mFooProperty = 0;
get FooProperty()
{
return mFooProperty;
}
set FooProperty(value)
{
mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
您可以在 Javascript 中使用 class 并将属性设置为 class 实例,然后使用 getters/setters like
class DemoClass {
constructor() {
this.mFooProperty = 0;
}
get FooProperty() {
return this.mFooProperty;
}
set FooProperty(value) {
this.mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
The bodies of class declarations and class expressions are executed in
strict mode
i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.
为了将 属性 的实际存储保留为私有变量,您必须使用对象 API 来定义 getter 和 setter 在构造函数中:
function DemoClass() {
var mFooProperty = 0;
Object.defineProperties(this, {
fooProperty: {
get: function() { return mFooProperty; },
set: function(value) { mFooProperty = value; }
}
});
}
现在当您构造一个实例时,该实例将显示为有一个名为 "fooProperty" 的 属性。引用 属性 的值将调用 "getter" 函数,设置该值将调用 "setter":
var d = new DemoClass();
console.log(d.fooProperty); // calls getter 0
d.fooProperty = 3; // calls setter
console.log(d.fooProperty); // 3