“嵌套” JavaScript 中的 getter 和 setter
我想使用 JS setters 和 getters 实现与此类似的语法:
globe.camera.position = Position.create();
这应该等同于这个表达式:
globe.getCamera().setPosition(Position.create());
我在创建 getters/setters 的“第一级”(.camera 部分)方面没有问题,如下所示:
function Camera() {
var x,y,z;
this.__defineGetter__("camera", function() {
alert("This is the camera getter");
});
this.__defineSetter__("camera", function(position) {
alert("This is the camera setter");
});
}
...
globe=new Camera();
globe.camera=...
c=globe.camera;
...
但我不太确定如何定义相机内的位置获取器。我正在尝试类似的方法,但它不起作用:
function Position() {
this.__defineGetter__("position", function() {
alert("This is the position getter");
});
}
globe.camera=new Position();
pos=globe.camera.position;
吸气剂内的警报不会显示。这有什么线索吗?有可能实现这种行为吗?我在 Google 上搜索了很多,但一直无法找到正确的搜索词,而且 getter/setter 的示例往往非常简单。提前致谢。
I want to achieve a syntax similar to this one using JS setters and getters:
globe.camera.position = Position.create();
This is supossed to be equivalent to this expression:
globe.getCamera().setPosition(Position.create());
I have no problem in creating the "first level" of getters/setters, the .camera part, like this:
function Camera() {
var x,y,z;
this.__defineGetter__("camera", function() {
alert("This is the camera getter");
});
this.__defineSetter__("camera", function(position) {
alert("This is the camera setter");
});
}
...
globe=new Camera();
globe.camera=...
c=globe.camera;
...
But im not quite sure on how to define the position getter inside camera. I am trying something like this but it wont work:
function Position() {
this.__defineGetter__("position", function() {
alert("This is the position getter");
});
}
globe.camera=new Position();
pos=globe.camera.position;
The alert inside the getter wont show up. Any clue on this? Is it even possible to achieve this behaviour? I have searched quite a lot on Google but havent been able to hit the right search terms, and the examples for getters/setters tend to be very simple. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
__defineGetter__
和朋友是非标准的。您可能想要使用
Object.defineProperty
但是,为什么要使用 getter 和 setter?他们是邪恶的。你真的应该避免它们,除非你做了一些聪明的事情。
__defineGetter__
and friends are non standard.Your going to want to use
Object.defineProperty
However, why are you using getters and setters? They are evil. You should avoid them really unless your doing something clever.