Introduction to javascript with s and s arbitration getter__ and s and s arbitration

  • 2020-03-30 03:43:20
  • OfStack

A Getter is a way to get the value of a property, and a Setter is a way to set the value of a property. You can add new properties to an existing object by defining getter and setter methods for any predefined core object or user-defined object.

There are two ways to define a Getter or Setter method:

1. Define when the object is initialized
2. Append the definition by using the Object's s method with s method

The only thing to do when using the object initialization process to define Getter and Setter methods is to put "get" in front of the Getter method and "set" in front of the Setter method.

Another thing to note is that the getter method has no arguments, and the setter method must have an argument, which is the new value of the property to set.

Such as:


   o = { 
        value:9, 
        get b() {return this.value;}, 
        set setter(x) {this.value = x;} 
    } 

Adding getter or setter methods to an object after the object is defined is done by using two special methods, namely, s method and s method. These two functions require that the first be the name of the getter or setter, given as a string, and the second argument be the function that ACTS as the getter or setter.

For example, we add a year attribute to the Date object:


Date.prototype.__defineGetter__('year', function() {return this.getFullYear();}); 
    Date.prototype.__defineSetter__('year', function(y) {this.setFullYear(y)}); 
     
    var now = new Date; 
    alert(now.year); 
    now.year = 2006; 
    alert(now);

As for which form to use, depending largely on the individual's programming style, the first form is more compact and easier to understand. But if you want to add a Getter or Setter after the object is defined, or if the prototype of the object is not written by you or a built-in object, then you have to go the other way.


Related articles: