开发常用-改造老项目监听属性变动

var obj = {

            name: 99,

            age: 777

        }

        function Watch(obj, prop) {

            var that = this;

            that.val = obj[prop];

            that.setFuns = [];

            Object.defineProperty(obj, prop, {

                get: function() {

                    console.log("get", prop, that.val)

                    return that.val

                },

                set: function(value) {

                    that.val = value;

                    console.log("set", prop, that.val)

                    that.setFuns.forEach(function(item) {

                        item(that.val);

                    });

                    return that.val;

                }

            })

        }

        Watch.prototype.addSetFuns = function(fn) {

            this.setFuns.push(fn);

        }

        var watch = new Watch(obj, "name");

        watch.addSetFuns(function(val) {

            alert(val)

        })

        setTimeout(function() {

            obj.name = 777

        }, 3000)

上一篇:vue-计算属性和监视属性


下一篇:妙用ES6解构和扩展运算符让你的代码更优雅