本文介绍了javascript属性值依赖于其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个名为Fullscreen的对象,并在对象内另一个名为directions的对象。所以我的代码如下所示:
I made an object called Fullscreen, and within the object another object called directions. so my code looks like this:
FullScreen = {
directions: {
prev: -1,
next: 1
}
}
但我想要能够从对象外部设置FullScreen.directions.prev,并将FullScreen.directions.next更改为prev的负值。任何想法如何做到这一点?
but i want to be able to set FullScreen.directions.prev from outside the object, and change FullScreen.directions.next to the negative value of the prev. any ideas how to do this?
推荐答案
如果我正确理解了这个问题,就像这样简单:
If I understand the question correctly, it's as simple as this:
FullScreen.directions.prev = -42;
FullScreen.directions.next = -FullScreen.directions.prev;
然而,将此逻辑封装在函数中可能会更好:
It might be better, however, to encapsulate this logic in a function:
FullScreen = {
directions: {
prev: -1,
next: 1,
setPrev: function (value) {
value = +value; // coerce to number
this.prev = value;
this.next = -value;
}
}
}
// then
FullScreen.direction.setPrev(-42);
您可以使用:
You could get even fancier using the special get/set
syntax:
FullScreen = {
directions: {
_prev: -1,
_next: 1,
get prev() {
return this._prev;
},
set prev(value) {
value = +value; // coerce to number
this._prev = value;
this._next = -value;
},
get next() {
return this._next;
}
}
}
// then
FullScreen.direction.prev = -42;
// invokes the setter function behind the scenes, so that _next is also set
这篇关于javascript属性值依赖于其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!