Can Javascript bind a callback function to a variable?
That is: when the value of this variable changes, the callback function is triggered and the content in the callback function is executed.
迷茫2017-06-26 10:55:29
var test = {
_age : 0,
methods:function(a)
{
console.log("发生变化了值为:"+a);
},
//_Age reading and writing
set age(age) {
if(age!=this._age)
{
this.methods(age);
this._age = age;
}},
get age() {return this._age;}
};
You can use the set and get methods of the object to perform the desired results
黄舟2017-06-26 10:55:29
Cannot be implemented directly.
But it can be achieved in other ways.
var obj = {
set: function (key, value) {
if(['set', 'change'].indexOf(key) > -1) return;
this[key] = value;
this.change();
},
};
obj.change = function(){
alert(1)
console.log(this);
}
obj.set('name', 'segmentfault');
// 将你需要的变量设为obj的一个属性
// 更改变量用obj.set()这个方法
淡淡烟草味2017-06-26 10:55:29
js set/get
You can add your logic code in the set method, so that your code will be triggered every time it is modified