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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.