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 spec和 on 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, orundefined
if there is no getter (accessor descriptors only).set
A function which serves as a setter for the property, orundefined
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/