问题描述
我仍然不觉得我完全理解Object.defineProperties的使用,所以我很欣赏以下(有点人为的)例子的一些输入:
I still don't feel like I completely understand the use of Object.defineProperties, so I'd appreciate some input on the following (somewhat contrived) examples:
var Class_1 = function (arg) {
this.my_val = arg;
};
var Class_2 = function (arg) {
Object.defineProperties(this,{
my_val : {
value : arg,
writable : true,
enumerable : true,
configurable : true
}
});
};
var one = new Class_1("foo");
var two = new Class_2("foo");
以及仅使用 defineProperties
的原因在Class_1中分配它就像你想要可写
,可枚举
或可配置
是假的;基本上它是为了控制。否则简单的 this.property
定义是相同的,对吗?
And the reasoning for using defineProperties
over just assigning it like in Class_1 would be when you want writable
, enumerable
or configurable
to be false; Basically it's for control. Otherwise the simple this.property
definition is identical, correct?
var Class_value = function (arg) {
Object.defineProperties(this, {
my_val : {
value : arg,
writable : true,
// enumerable : false // default
// configurable : false // default
}
});
};
var Class_getSet = function (arg) {
Object.defineProperties(this, {
__my_val : {
value : arg,
writable : true,
// enumerable : false // default
// configurable : false // default
},
my_val : {
get : function(){ return this.__my_val; },
set : function(new_val){ this.__my_val = new_val; }
}
});
};
var three = new Class_value("foo");
var four = new Class_getSet("foo");
使用获取
/ 设置函数只需值
就可以添加更多高级逻辑,例如在<$ c $时调用另一个函数c> my_val 已更新,或发送事件等。此外,您无法使用获取
/ 设置
至少没有定义初始值(通过此处显示的值
属性,或通过简单的 this.property = ...
定义如 1。),对吗?
And the reasoning for using get
/set
functions over just value
would be when you want to add more advanced logic, like calling another function when my_val
is updated, or sending an event, etc. Also you cannot use get
/set
without at least defining the initial value (either via a value
property shown here, or via the simple this.property = ...
definition as in 1.), correct?
基本上我我只是想确保我理解如何以及何时使用defineProperties的原因,因为我觉得我还没有很好地处理这个概念。
Basically I'm just looking to make sure that I understand the reasoning for how and when to use defineProperties, since I feel like I don't have a good handle on the concept yet.
推荐答案
是的。
不 - 有 __ my_val
。您至少可以考虑使用本地范围的私有变量而不是公共属性。
No - there's __my_val
. You might at least consider using a local-scoped, "private" variable instead of a public property.
是的,这就是的用途。
不,你可以简单地留下它 undefined
以及。
No, you could simply leave it undefined
as well.
这篇关于澄清Javascript Object.defineProperties的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!