[英]Is it safe to use “get” and “set” as property names in javascript?
Is it generally safe to use get and set as the names of properties for an object literal, like this: 使用get并将其设置为对象文字的属性名称通常是安全的,如下所示:
var myObject={
get: 'value1',
set: 'value2'
}
Get and set do not appear to be reserved words in javascript, but I'm worried this could cause clashes with some built-in behaviors. 获取和设置似乎不是javascript中的保留字,但我担心这可能会导致与某些内置行为发生冲突。 In particular get and set seem to have some pretty unique behavior in the Object.defineProperties
method : 特别是get和set似乎在Object.defineProperties
方法中有一些非常独特的行为 :
Object.defineProperties(someObject,{
'Property1':{
get:function(){
return property1;
},
set:function(val){
property1=val;
},
enumerable:true;
}
});
In this built-in behavior, the get
and set
aren't treated as normal properties but actually execute their respective functions when someObject.Property1
is accessed or assigned to. 在这种内置行为中, get
和set
不被视为普通属性,但实际上在访问或分配someObject.Property1
时执行它们各自的函数。
Because of how they're used in Object.defineProperties
I've always sort of treated get
and set
as special reserved words. 因为他们是如何在使用Object.defineProperties
我一直有点对待get
和set
特殊的保留字。 So my question is, is that a good rule of thumb or should I just learn to stop worrying and just use get
and set
whenever it seems semantically appropriate? 所以我的问题是,这是一个很好的经验法则还是我应该学会停止担心,只要在语义上合适时使用get
和set
?
Yes, it's safe. 是的,这很安全。 get
and set
are always treated as normal properties. get
和set
始终被视为普通属性。 The fact that they are used to define getters and setters in property descriptors is completely irrelevant. 它们用于在属性描述符中定义getter和setter这一事实完全无关紧要。
An example of an unsafe property would be valueOf
, because it actually changes how an object behaves: 不安全属性的一个示例是valueOf
,因为它实际上更改了对象的行为方式:
console.log(+{}); // NaN
console.log(+{ valueOf: () => 5 }); // 5
The fact that get
and set
are valid properties in the object you pass to Object.defineProperties
is proof that it's safe to use get
and set
as property names. get
和set
是传递给Object.defineProperties
的对象中的有效属性,这一Object.defineProperties
证明使用get
和set
作为属性名称是安全的。
The only time get
and set
have a special meaning in JavaScript is when you're creating a getter or setter , but the syntax is different, so there isn't a clash with property names. get
和set
唯一具有特殊含义的是当你创建一个getter或setter时 ,但是语法不同,所以没有与属性名冲突。
在javascript 描述的setter getter机制中,我没有看到任何冲突或理由认为它不安全,除非其他人也这样做,所以要小心覆盖其他库,以便它是好的去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.