浅谈在JS中运用Object的watch要领监控对象属性

MDN 对其的解释为:

概述:
    看管一个对象的某个属性是不是发生变化,在该属性变化时马上触发指定的回调函数.
语法:
    object.watch(prop, handler)
参数:
    prop
    想要看管值是不是发生变化的指定对象的某个属性的属性称号
    handler
    当指定的属性发生变化时实行的回调函数

在 DHTML.js内检察其声明以下:

《浅谈在JS中运用Object的watch要领监控对象属性》
能够看到这两个要领是只针对 Gecko 内核的浏览器运用的(FF 是运用的 Gecko 内核).
wacth 要领有两个参数,第一个参数是一个字符串,代表须要看管的属性名,第二个参数是个回调函数
unwatch 要领只要一个参数,代表须要作废看管的属性名.

运用举例:

var o = {p:1};
o.watch("p", function (id, oldValue, newValue) {
    console.log("o."+id +" 由 "+oldValue +" 变成 "+newValue);
    return newValue;//注重点
});
o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

输出效果为:
《浅谈在JS中运用Object的watch要领监控对象属性》
这里须要注重的是回调函数必需返回一个值,返回的值会掩盖原有的值(若无返回值默许返回的是 undefined),能够返回新值

运用watch 要领来看管对象的属性

//声明一个类
Person = function (name, age) {
    this.watch("age",Person.prototype._isValidAssignment);
    this.watch("name",Person.prototype._isValidAssignment);
    this.name = name;
    this.age = age;
};

Person.prototype.toString = function () {
    return this.name + " , " + this.age;
};
//定义语义上的私有要领
Person.prototype._isValidAssignment = function(id,oldVale,newValue){
    if(id == "name" && (!newValue || newValue.length > 30)){
        throw new RangeError("不合法的名字 "+ this);
    }
    if(id == "age" && (newValue <0 || newValue >200)){
        throw new RangeError("不合法的岁数 "+ this);
    }
    return newValue;//重点,必需返回
}

will = new Person("will",29);
console.log(will);

try{
    will.name = "";
}catch(e){
    console.log(e);
}

try{
    will.age = -4;
}catch(e){
    console.log(e);
}

输出效果以下:
《浅谈在JS中运用Object的watch要领监控对象属性》

末了引入 MDN 的一段形貌与注重事项

《浅谈在JS中运用Object的watch要领监控对象属性》

    原文作者:Tomson
    原文地址: https://segmentfault.com/a/1190000003853741
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞