javascript - 在文字对象中创建属性

标签 javascript

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对象内部呢?那是一种方法或属性还是其他什么? 它是如何工作的,或者它如何将属性或方法设置为对象?如果我简单地忽略 get 的使用,我会遇到麻烦吗?和 set ?使用 get 是否有更多优势?和 set而不是简单地定义属性而没有使用。如果有的话,这些优点是什么。另外,.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 而不是 get 来做到这一点。 :-)

您可以在 object initializers 中阅读更多相关信息规范的一部分,以及 on MDN .

Object.getOwnPropertyDescriptor 调用返回一个描述您请求的属性的对象(在本例中为 foo)。您可以阅读更多相关信息 in the specon MDN

引用自 MDN:

A property descriptor is a record (TJC: e.g., object) with some of the following attributes:

value
The value associated with the property (data descriptors only).
writable
true if and only if the value associated with the property may be changed (data descriptors only).
get
A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only).
set
A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only).
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.

关于javascript - 在文字对象中创建属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16265055/

相关文章:

javascript - 如何根据日期对对象数组进行排序

javascript - FB Connect 对话框未关闭

javascript - 使用 Google Drive SDK 上传 JSON 文件是零字节(javascript)

javascript - 以编程方式打开 Kube CSS 框架消息警报

javascript - 按日期检查jquery中是否是假期的功能

javascript - 使用下拉列表 jquery 插件过滤页面上的 div

javascript - 单击按钮时的appendChild()问题

javascript - 在 AngularJS 中传递这个参数

javascript - D3 带过渡的多线图

javascript - php - 如果选择单选按钮,则从数据库表中选择值