[英]Defining non-writable properties without Object.defineProperty?
So I know you can do this: 所以我知道你可以这样做:
var obj = {};
Object.defineProperty(obj, 'staticProp', {
value: 'I will never change',
writable: 'false'
});
And I know you can do this: 而且我知道你可以这样做:
var obj = {
get gettableProp(){
return 'gettable!'
}
}
Is there a way to define non-writable/enumerable/configurable properties declaratively instead of using Object.defineProperty(), the way you'd define a getter or setter? 有没有办法以声明方式定义不可写/可枚举/可配置属性,而不是使用Object.defineProperty(),你定义一个getter或setter的方式?
The reason I ask is because I have a function that gets passed an object like this: 我问的原因是因为我有一个传递像这样的对象的函数:
ObjectProcessor({
// A bunch of properties
})
I'd really like to be able to keep that simple syntax for cases when I'd want to include non-writable or non-enumerable properties, rather than having to do 当我想要包含不可写或不可枚举的属性时,我真的希望能够保留这种简单的语法,而不是必须这样做
var obj = {}
Object.defineProperty(obj, 'staticProp', {
value: 'I will never change',
writable: 'false'
});
ObjectProcessor(obj);
Is there a way to define non-writable/enumerable/configurable properties declaratively instead of using Object.defineProperty(), the way you'd define a getter or setter?
有没有办法以声明方式定义不可写/可枚举/可配置属性,而不是使用Object.defineProperty(),你定义一个getter或setter的方式?
No. 没有。
(there is Object.defineProperties
, but I guess that's not what you are looking for) (有
Object.defineProperties
,但我猜这不是你想要的)
No, there is no other method (except for Object.defineProperties
and Object.create
that allow you to provide multiple of these descriptors). 不,没有其他方法(
Object.defineProperties
和Object.create
除外,它允许您提供多个这些描述符)。
I'd really like to be able to keep that simple syntax
我真的希望能够保持这种简单的语法
Notice that Object.defineProperty
returns the passed object, so you can simplify your code to 请注意,
Object.defineProperty
返回传递的对象,因此您可以将代码简化为
ObjectProcessor(Object.defineProperty({}, 'staticProp', {
value: 'I will never change',
writable: 'false'
}));
and avoid introducing that extra obj
variable. 并避免引入额外的
obj
变量。
With a naming convention, you can build it into your ObjectProcessor: 使用命名约定,您可以将其构建到ObjectProcessor中:
var prefix = 'readonly_';
function ObjectProcessor(obj) {
Object.keys(obj).filter(function (name) {
// find property names which match your convention
return name.indexOf(prefix) === 0;
}).forEach(function (name) {
// make the new property readonly
Object.defineProperty(obj, name.substring(prefix.length), {
value: obj[name],
writable: false
});
// remove the old, convention-named property
delete obj[name];
});
// remaining ObjectProcessor logic...
}
This lets you handle writable and readonly properties: 这使您可以处理可写和只读属性:
ObjectProcessor({
readonly_id: 1,
name: 'Foo'
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.