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.
擁有18年軟件開發(fā)和IT教學經驗。曾任多家上市公司技術總監(jiān)、架構師、項目經理、高級軟件工程師等職務。 網絡人氣名人講師,...
var test = {
_age : 0,
methods:function(a)
{
console.log("發(fā)生變化了值為:"+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
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()這個方法
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