Sample code sharing for getter/setter implementation in JavaScript
Although ES5 provides us with the Object.defineProperty method to set getters and setters, this native method is inconvenient to use. Why not implement a class ourselves, as long as inheritThis class and following certain specifications can have getters and setters that are comparable to native ones.
Now we define the following specifications:
The valuer and the setter follow the format: _xxxGetter/_xxxSetter, xxx represents the attribute that needs to be controlled. For example, if you want to control the foo attribute, the object needs to provide the _fooGetter/_fooSetter method as the actual valuer and controller, so that we can call obj.get in the code ('foo') and obj.set('foo', value) to get and set the value; otherwise, calling the get and set methods is equivalent to the code: obj.foo and obj.foo = value;
Provide watchfunction: obj.watch(attr, function(name, oldValue, newValue){}); Each time the set method is called, the fucntion parameter will be triggered. The name in the function represents the changed attribute, oldValue is the last value of the attribute, and newValue represents the latest value of the attribute. This method returns a handle object with a remove method. Call remove to remove the function parameter from the function chain.
First use closureMode, and use attributes variables as private attributes to store the getters and setters of all attributes:
var Stateful = (function(){ 'use strict'; var attributes = { Name: { s: '_NameSetter', g: '_NameGetter', wcbs: [] } }; var ST = function(){}; return ST; })()
where wcbs is used to store All callbacks when calling watch(name, callback).
The first version of the implementation code is as follows:
var Stateful = (function(){ 'use strict'; var attributes = {}; function _getNameAttrs(name){ return attributes[name] || {}; } function _setNameAttrs(name) { if (!attributes[name]) { attributes[name] = { s: '_' + name + 'Setter', g: '_' + name + 'Getter', wcbs: [] } } } function _setNameValue(name, value){ _setNameAttrs(name); var attrs = _getNameAttrs(name); var oldValue = _getNameValue.call(this, name); //如果对象拥有_nameSetter方法则调用该方法,否则直接在对象上赋值。 if (this[attrs.s]){ this[attrs.s].call(this, value); } else { this[name] = value; } if (attrs.wcbs && attrs.wcbs.length > 0){ var wcbs = attrs.wcbs; for (var i = 0, len = wcbs.length; i < len; i++) { wcbs[i](name, oldValue, value); } } }; function _getNameValue(name) { _setNameAttrs(name); var attrs = _getNameAttrs(name); var oldValue = null; // 如果拥有_nameGetter方法则调用该方法,否则直接从对象中获取。 if (this[attrs.g]) { oldValue = this[attrs.g].call(this, name); } else { oldValue = this[name]; } return oldValue; }; function ST(){}; ST.prototype.set = function(name, value){ //每次调用set方法时都将name存储到attributes中 if (typeof name === 'string'){ _setNameValue.call(this, name, value); } else if (typeof name === object) { for (var p in name) { _setNameValue.call(this, p, name[p]); } } return this; }; ST.prototype.get = function(name) { if (typeof name === 'string') { return _getNameValue.call(this, name); } }; ST.prototype.watch = function(name, wcb) { var attrs = null; if (typeof name === 'string') { _setNameAttrs(name); attrs = _getNameAttrs(name); attrs.wcbs.push(wcb); return { remove: function(){ for (var i = 0, len = attrs.wcbs.length; i < len; i++) { if (attrs.wcbs[i] === wcb) { break; } } attrs.wcbs.splice(i, 1); } } } else if (typeof name === 'function'){ for (var p in attributes) { attrs = attributes[p]; attrs.wcbs.splice(0,0, wcb); //将所有的callback添加到wcbs数组中 } return { remove: function() { for (var p in attributes) { var attrs = attributes[p]; for (var i = 0, len = attrs.wcbs.length; i < len; i++) { if (attrs.wcbs[i] === wcb) { break; } } attrs.wcbs.splice(i, 1); } } } } }; return ST; })()
Test work:
console.log(Stateful); var stateful = new Stateful(); function A(name){ this.name = name; }; A.prototype = stateful; A.prototype._NameSetter = function(n) { this.name = n; }; A.prototype._NameGetter = function() { return this.name; } function B(name) { this.name = name; }; B.prototype = stateful; B.prototype._NameSetter = function(n) { this.name = n; }; B.prototype._NameGetter = function() { return this.name; }; var a = new A(); var handle = a.watch('Name', function(name, oldValue, newValue){ console.log(name + 'be changed from ' + oldValue + ' to ' + newValue); }); a.set('Name', 'AAA'); console.log(a.name); var b = new B(); b.set('Name', 'BBB'); console.log(b.get('Name')); handle.remove(); a.set('Name', 'new AAA'); console.log(a.get('Name'), b.get('Name'))
Output:
function ST(){} Namebe changed from undefined to AAA AAA Namebe changed from undefined to BBB BBB new AAA BBB
You can see that all watch functions are stored in the wcbs array , all properties with the same name in subclasses access the same wcbs array. Is there any way to ensure that each instance has its own watch function chain without causing pollution? You can consider this method: add a _watchCallbacks attribute to each instance, which is a function, and store all watch function chains in this function. The main code is as follows:
ST.prototype.watch = function(name, wcb) { var attrs = null; var callbacks = this._watchCallbacks; if (!callbacks) { callbacks = this._watchCallbacks = function(n, ov, nv) { var execute = function(cbs){ if (cbs && cbs.length > 0) { for (var i = 0, len = cbs.length; i < len; i++) { cbs[i](n, ov, nv); } } } //在函数作用域链中可以访问到callbacks变量 execute(callbacks['_' + n]); execute(callbacks['*']);// 通配符 } } var _name = ''; if (typeof name === 'string') { var _name = '_' + name; } else if (typeof name === 'function') {//如果name是函数,则所有属性改变时都会调用该函数 _name = '*'; wcb = name; } callbacks[_name] = callbacks[_name] ? callbacks[_name] : []; callbacks[_name].push(wcb); return { remove: function(){ var idx = callbacks[_name].indexOf(wcb); if (idx > -1) { callbacks[_name].splice(idx, 1); } } }; };
After the change, the whole The code is as follows:
var Stateful = (function(){ 'use strict'; var attributes = {}; function _getNameAttrs(name){ return attributes[name] || {}; } function _setNameAttrs(name) { if (!attributes[name]) { attributes[name] = { s: '_' + name + 'Setter', g: '_' + name + 'Getter'/*, wcbs: []*/ } } } function _setNameValue(name, value){ if (name === '_watchCallbacks') { return; } _setNameAttrs(name); var attrs = _getNameAttrs(name); var oldValue = _getNameValue.call(this, name); if (this[attrs.s]){ this[attrs.s].call(this, value); } else { this[name] = value; } if (this._watchCallbacks){ this._watchCallbacks(name, oldValue, value); } }; function _getNameValue(name) { _setNameAttrs(name); var attrs = _getNameAttrs(name); var oldValue = null; if (this[attrs.g]) { oldValue = this[attrs.g].call(this, name); } else { oldValue = this[name]; } return oldValue; }; function ST(obj){ for (var p in obj) { _setNameValue.call(this, p, obj[p]); } }; ST.prototype.set = function(name, value){ if (typeof name === 'string'){ _setNameValue.call(this, name, value); } else if (typeof name === 'object') { for (var p in name) { _setNameValue.call(this, p, name[p]); } } return this; }; ST.prototype.get = function(name) { if (typeof name === 'string') { return _getNameValue.call(this, name); } }; ST.prototype.watch = function(name, wcb) { var attrs = null; var callbacks = this._watchCallbacks; if (!callbacks) { callbacks = this._watchCallbacks = function(n, ov, nv) { var execute = function(cbs){ if (cbs && cbs.length > 0) { for (var i = 0, len = cbs.length; i < len; i++) { cbs[i](n, ov, nv); } } } //在函数作用域链中可以访问到callbacks变量 execute(callbacks['_' + n]); execute(callbacks['*']);// 通配符 } } var _name = ''; if (typeof name === 'string') { var _name = '_' + name; } else if (typeof name === 'function') {//如果name是函数,则所有属性改变时都会调用该函数 _name = '*'; wcb = name; } callbacks[_name] = callbacks[_name] ? callbacks[_name] : []; callbacks[_name].push(wcb); return { remove: function(){ var idx = callbacks[_name].indexOf(wcb); if (idx > -1) { callbacks[_name].splice(idx, 1); } } }; }; return ST; })()
Test:
console.log(Stateful); var stateful = new Stateful(); function A(name){ this.name = name; }; A.prototype = stateful; A.prototype._NameSetter = function(n) { this.name = n; }; A.prototype._NameGetter = function() { return this.name; } function B(name) { this.name = name; }; B.prototype = stateful; B.prototype._NameSetter = function(n) { this.name = n; }; B.prototype._NameGetter = function() { return this.name; }; var a = new A(); var handle = a.watch('Name', function(name, oldValue, newValue){ console.log(name + 'be changed from ' + oldValue + ' to ' + newValue); }); a.set('Name', 'AAA'); console.log(a.name); var b = new B(); b.set('Name', 'BBB'); console.log(b.get('Name')); a.watch(function(name, ov, nv) { console.log('* ' + name + ' ' + ov + ' ' + nv); }); a.set({ foo: 'FOO', goo: 'GOO' }); console.log(a.get('goo')); a.set('Name', 'AAA+'); handle.remove(); a.set('Name', 'new AAA'); console.log(a.get('Name'), b.get('Name'))
Output:
function ST(obj){ for (var p in obj) { _setNameValue.call(this, p, obj[p]); } } Namebe changed from undefined to AAA AAA BBB * foo undefined FOO * goo undefined GOO GOO Namebe changed from AAA to AAA+ * Name AAA AAA+ * Name AAA+ new AAA new AAA BBB
#
The above is the detailed content of Sample code sharing for getter/setter implementation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
