JS object - xuanz1993/JS GitHub Wiki

Javascript Object

  1. property getters and setters
  • The value of one property can be replaced by one or two methods, known as a setter and a getter. The property defined by getters and setters are sometimes known as accessor property.
  • Queries the value of an accessor property, invokes the getter method; Set the value of an accessor property,invokes the setter method.
  • Accessor property does not have a writable attribute as data property.
  • getter/setter example:
var p = {
    x:1.0;
    y:1.0;
    get r(){return Math.sqrt(this.x*this.x+this.y*this.y);},
    set r(newValue){
        var oldValue = Math.sqrt(this.x*this.x+this.y*this.y);
        var ratio = newValue/oldValue;
        this.x *= ratio;
        this.y *= ratio;
    }
}
  1. Property Attributes
  • Attributes can specify the property can be writable, enumerated, and configured.
  • Use API to query and set property attributes. In order to:
    • make added methods nonenumerable
    • lock objects
  • Data property attributes: value, writable, enumerated, configurable
  • Accessor property: getter, setter, enumerated, configurable
  • To obtain the property descriptor for a named property of a specific object, call object.getOwnPropertyDescriptor(), works only for own properties.