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 = 'z:bind'; 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 === 'INPUT'){ ele.value = value; }else{ ele.innerHTML = value; } data[argKey] = value; } }); arg[argKey] = arg[argKey]; }); var key = ele.getAttribute(bindAttributeName); if((ele.tagName === 'INPUT' || ele.tagName === 'TEXTAREA') && arg[key]){ ele.addEventListener('input', function(e){ data[key] = ele.value; }); } } /* 例子很简单,直接改变对象属性,就直接 反馈到了DOM上,就好像是一个钩子,改变 这个对象的属性,这个属性的钩子把它绑 定的DOM的数据进行修改 */ var start = (new Date()).getTime(); var now; var b = {time: '0s'}; bind_data(document.getElementById('testTime'), b); setInterval(function(){ var now = (new Date()).getTime(); b.time = ((now - start)/1000) + 's' }, 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!