Home >Web Front-end >JS Tutorial >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!