Creating properties in a literal object

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 }

What does this getinside the object do? Is this a method or property or something else? How does it work or how does it set a property or method of an object? Will I get into trouble if I just ignore the use of getand set? Are there more advantages to using getand setthan just defining a property without using. What are these benefits, if any. will the method be returned .getOwnPropertyDescriptor()? If it returns an object, can I just do it returnedobj.configurableto access a custom property value?

+5
source share
2 answers

get . foo o, , , :

var a = o.foo; // Note that `foo` doesn't have () after it, it 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.: -)

, MDN.

Object.getOwnPropertyDescriptor , ( foo). MDN .

MDN:

(TJC: , ) :

value
, ( ).
writable
true , , , ( ).
get
, getter , undefined, ( ).
set
, , undefined, ( ).
configurable
true , .
enumerable
true , .

+4

get ECMAScript 5 getters seters.

, :

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

getter .

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

foo __other_property__. - , , , , .

+2

All Articles