Home  >  Article  >  Web Front-end  >  Basic introduction to getters and setters in Javascript

Basic introduction to getters and setters in Javascript

巴扎黑
巴扎黑Original
2017-08-18 10:52:561533browse

I recently encountered getters and setters at work. Getters are a method of obtaining attribute values, and setters are a method of setting attribute values. The following article mainly introduces you to the relevant information about getters and setters in Javascript. Friends who need it can refer to it. Let’s take a look together.

Preface

This article mainly introduces you to the related content of getters and setters in Javascript. When I first heard about this thing It is data binding in vue.js. As long as the data is bound, modified object properties can be automatically fed back to the dom. It is amazing. Later, I also saw that the implementation in the document defines getters and setters for the object and overwrites the original properties. Simply Let’s summarize the usage of these two. I won’t say much below, let’s take a look at the detailed introduction.

Principle

Use Object.defineProperty to rewrite object properties as getters and setters, and change the bound DOM nodes through getters and setters. Value

Example

Excerpted from MDN


function Archiver() {
 var temperature = null;
 var archive = [];

 Object.defineProperty(this, 'temperature', {
  get: function() {
   console.log('get!');
   return temperature;
  },
  set: function(value) {
   temperature = value;
   archive.push({ val: temperature });
  }
 });

 this.getArchive = function() { return archive; };
}

var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]

Use this MDN example for a small I wrote a method and a timer DEMO


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1 id="testTime" z:bind="time">0s</h1>
<script>

  // 双向绑定
  function bind_data(ele, arg){
    var bindAttributeName = &#39;z:bind&#39;;
    var data = JSON.parse(JSON.stringify(arg)) || {};
    Object.keys(arg).forEach(function(argKey, index, array){
      Object.defineProperty(arg, argKey, {
        get: function(){
          return data[argKey];
        },
        set: function(value){
          if(ele.getAttribute(bindAttributeName) !== argKey) {
            return;
          }
          if(ele.tagName === &#39;INPUT&#39;){
            ele.value = value;
          }else{
            ele.innerHTML = value;
          }
          data[argKey] = value;
        }
      });
      arg[argKey] = arg[argKey];
    });
    var key = ele.getAttribute(bindAttributeName);
    if((ele.tagName === &#39;INPUT&#39; || ele.tagName === &#39;TEXTAREA&#39;) && arg[key]){
      ele.addEventListener(&#39;input&#39;, function(e){
        data[key] = ele.value;
      });
    }
  }


  /*
  例子很简单,直接改变对象属性,就直接
  反馈到了DOM上,就好像是一个钩子,改变
  这个对象的属性,这个属性的钩子把它绑
  定的DOM的数据进行修改
   */ 
  var start = (new Date()).getTime();
  var now;
  var b = {time: &#39;0s&#39;};
  bind_data(document.getElementById(&#39;testTime&#39;), b);
  setInterval(function(){
    var now = (new Date()).getTime();
    b.time = ((now - start)/1000) + &#39;s&#39;
  }, 1);

</script>
</body>
</html>

The above is the detailed content of Basic introduction to getters and setters in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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