在文字对象中创建属性

Creating properties in literal object

本文关键字:创建 属性 对象 文字      更新时间:2023-09-26
var o, d;
o = { get foo() { return 17; } };
d = Object.getOwnPropertyDescriptor(o, "foo");
// d is { configurable: true, enumerable: true, get: /*the getter function*/, set:     undefined }

对象中的get做什么?这是一个方法,属性还是别的什么?它是如何工作的或者它是如何为对象设置属性或方法的?如果我简单地忽略getset的使用是否会遇到麻烦?使用getset是否比简单地定义属性而不使用它们更有优势?如果有的话,这些优势是什么?.getOwnPropertyDescriptor()方法也会返回什么?如果它返回对象,我可以简单地做returnedobj.configurable访问可配置的属性值吗?

get定义了一个属性访问器函数。当检索到o上的foo属性的值时,即使它在代码中看起来不像函数调用,也会调用该函数,例如:

var a = o.foo; // Note that `foo` doesn't have () after it, it's not a function call

在本例中,它总是返回17,但它可以做其他事情。例如,考虑一个圆:

var circle = {
    radius: 7,
    get circumference() { return 2 * Math.PI * this.radius; },
    get area()          { return Math.PI * this.radius * this.radius; }
};
console.log(circle.circumference); // 43.982297150257104 
console.log(circle.area);          // 153.93804002589985 
circle.radius = 4;
console.log(circle.circumference); // 25.132741228718345
console.log(circle.area);          // 50.26548245743669 

可以看到,当我们访问用访问器定义的两个属性时,分配给它们的函数被调用,尽管属性访问看起来不像函数调用。

也可以让函数在属性为set时被调用。不出所料,您使用set而不是get来做到这一点。: -)

您可以在规范的对象初始化器部分和MDN中阅读更多相关内容。

Object.getOwnPropertyDescriptor调用返回一个对象,该对象描述了您请求的属性(在本例中为foo)。你可以在规范和MDN上阅读更多关于它的信息。

引用自MDN:

属性描述符是一个记录(TJC:例如,对象),具有以下一些属性:

value
与属性关联的值(仅限数据描述符)。
writable
true当且仅当与属性相关的值可以更改时(仅限数据描述符)。
get
作为属性的getter的函数,如果没有getter(只有访问描述符),则为undefined
set
作为属性的设置器的函数,如果没有设置器,则为undefined(仅为访问描述符)。
configurable
true当且仅当此属性描述符的类型可以更改,且该属性可以从对应对象中删除时。
enumerable
true当且仅当此属性在枚举相应对象的属性时出现。

get是ECMAScript 5语法的一部分,用于定义属性getter和setter。

使用对象字面语法,它的定义如下:

var obj = {
    __other_property__: null,
    get foo() { return "bar"; },
    set foo(v) { this.__other_property__ = v }
};

这允许你在对属性执行get操作时调用getter函数体。

obj.foo = "oof";
console.log(obj.foo); // "bar"
console.log(obj.__other_property__); // "oof"

上面使用foo来设置一个不同的属性__other_property__。这可以是一个局部变量或其他东西,函数显然可以做比我在这里展示的复杂得多的操作。