Home > Web Front-end > JS Tutorial > A daily javascript learning summary (attribute definition method)_javascript skills

A daily javascript learning summary (attribute definition method)_javascript skills

WBOY
Release: 2016-05-16 15:31:15
Original
1409 people have browsed it

Definition. To define attributes, you need to use the corresponding function, such as:
Object.defineProperty(obj, "prop", propDesc)
If obj does not have its own attribute prop, the function of this function is to add its own attribute prop to obj and assign a value,
The parameter propDesc ​​specifies the characteristics of the attribute (writability, enumerability, etc.).
If obj already has its own attribute prop, the function of this function is to modify the characteristics of the existing attribute, including its attribute value.
1. defineProperty 

 var book = {
   _year: 2004,
   edition: 1
  };
   
  Object.defineProperty(book, "year", {
   get: function(){
    return this._year;
   },
   set: function(newValue){
   
    if (newValue > 2004) {
     this._year = newValue;
     this.edition += newValue - 2004;
    
    }
   }
  });
  
  book.year = 2005;
  alert(book.edition); //2
Copy after login

2. __defineSetter__ and __defineGetter__

 var book = {
   _year: 2004,
   edition: 1
  };
   
  //legacy accessor support
  book.__defineGetter__("year", function(){
   return this._year; 
  });
  
  book.__defineSetter__("year", function(newValue){
   if (newValue > 2004) {
    this._year = newValue;
    this.edition += newValue - 2004;
   } 
  });

  
  book.year = 2005;
  alert(book.edition); //2
Copy after login

The above is today’s summary of JavaScript learning, and it will continue to be updated every day. I hope you will continue to pay attention.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template