Home > Web Front-end > JS Tutorial > body text

Sample code sharing for getter/setter implementation in JavaScript

黄舟
Release: 2017-03-13 17:13:41
Original
1310 people have browsed it

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;
})()
Copy after login

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 === &#39;string&#39;){
            _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 === &#39;string&#39;) {
            return _getNameValue.call(this, name);
        }
    };

    ST.prototype.watch = function(name, wcb) {
        var attrs = null;
        if (typeof name === &#39;string&#39;) {
            _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 === &#39;function&#39;){
            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;
})()
Copy after login

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(&#39;Name&#39;, function(name, oldValue, newValue){
        console.log(name + &#39;be changed from &#39; + oldValue + &#39; to &#39; + newValue);
    });
    a.set(&#39;Name&#39;, &#39;AAA&#39;);
    console.log(a.name);

    var b = new B();
    b.set(&#39;Name&#39;, &#39;BBB&#39;);
    console.log(b.get(&#39;Name&#39;));

    handle.remove();
    a.set(&#39;Name&#39;, &#39;new AAA&#39;);
    console.log(a.get(&#39;Name&#39;), b.get(&#39;Name&#39;))
Copy after login

Output:

function ST(){}
Namebe changed from undefined to AAA
AAA
Namebe changed from undefined to BBB
BBB
new AAA BBB
Copy after login

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[&#39;_&#39; + n]);
                execute(callbacks[&#39;*&#39;]);// 通配符
            }
        }

        var _name = &#39;&#39;;
        if (typeof name === &#39;string&#39;) {
            var _name = &#39;_&#39; + name;
        } else if (typeof name === &#39;function&#39;) {//如果name是函数,则所有属性改变时都会调用该函数
            _name = &#39;*&#39;;
            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);
                }
            }
        };
    };
Copy after login

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[&#39;_&#39; + n]);
                execute(callbacks[&#39;*&#39;]);// 通配符
            }
        }

        var _name = &#39;&#39;;
        if (typeof name === &#39;string&#39;) {
            var _name = &#39;_&#39; + name;
        } else if (typeof name === &#39;function&#39;) {//如果name是函数,则所有属性改变时都会调用该函数
            _name = &#39;*&#39;;
            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;
})()
Copy after login

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(&#39;Name&#39;, function(name, oldValue, newValue){
        console.log(name + &#39;be changed from &#39; + oldValue + &#39; to &#39; + newValue);
    });
    a.set(&#39;Name&#39;, &#39;AAA&#39;);
    console.log(a.name);

    var b = new B();
    b.set(&#39;Name&#39;, &#39;BBB&#39;);
    console.log(b.get(&#39;Name&#39;));

    a.watch(function(name, ov, nv) {
        console.log(&#39;* &#39; + name + &#39; &#39; + ov + &#39; &#39; + nv);
    });

    a.set({
        foo: &#39;FOO&#39;,
        goo: &#39;GOO&#39;
    });

    console.log(a.get(&#39;goo&#39;));

    a.set(&#39;Name&#39;, &#39;AAA+&#39;);

    handle.remove();
    a.set(&#39;Name&#39;, &#39;new AAA&#39;);
    console.log(a.get(&#39;Name&#39;), b.get(&#39;Name&#39;))
Copy after login

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
Copy after login











#

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!