ES6:构造函数 getter 和 setter
为什么我不能在构造函数中以这种方式设置 getter 和 setter?
function zConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
set fullname(text) {
const parts = text.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
get fullname() {
return this.firstName + ' ' + this.lastName;
}
}
这种 getter 和 setter 方式仅适用于类和工厂函数。原因是什么?
谢谢!
Why can't I set getters and setters in this way inside of the Constructor function?
function zConstructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
set fullname(text) {
const parts = text.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
get fullname() {
return this.firstName + ' ' + this.lastName;
}
}
This getters and setters way works only in classes and Factory functions. What is the reason?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以做到这一点,但是构造函数只是一个函数,普通代码块的语法不包括setter和getter函数的创建;就解析器而言,甚至无法理解代码的含义。
您可以使用
Object.defineProperties()
添加属性。或者,更好的方法是直接在原型上创建它们(再次使用Object.defineProperties()
),或者使用class
声明:You can do it, but a constructor function is just a function, and the syntax of ordinary code blocks does not include the creation of setter and getter functions; there's no way to even make sense of what your code is supposed to mean, as far as the parser is concerned.
What you can do is use
Object.defineProperties()
to add the properties. Or, probably better, is to create them on the prototype either directly (again, withObject.defineProperties()
), or by using aclass
declaration:执行此操作的正确方法是:
您的代码不起作用,因为 setter 和 getter 仅对对象有意义。
A proper way of doing this is:
Your code does not work because setters and getters are meaningful for Objects only.