首页 > 试题广场 >

js监听对象属性的改变

[问答题]

ES5:通过getter和setter

var obj={};

Object.defineProperty(obj,'data',{

__get:function(){

____return data;

__},

__set:function(newValue){

____data=newValue;

____console.log('set :',newValue);

____//需要触发的渲染函数写在这...

__}

})

// 测试

obj.data=5; //set: 5

//同时定义多个变量的setter和getter

var obj = {};

Object.defineProperties(obj, {

__a: {

____configurable: true, //表示该属性描述符可以被改变(默认为false)

____get: function() {

______console.log('get: ',a)

______return a

____},

____set: function(newValue) {

______a = newValue;

______console.log('set: ',a)

____}

__},

__b: {

____configurable: true,

____get: function() {

______console.log('get: ',b)

______return b;

____},

____set: function(newValue) {

______b = newValue;

______console.log('set: ',b)

____}

__}

})

---------------------------------------------

ES6:Proxy

let validator = {

__set: function(obj, prop, value) {

____if (prop === 'age') {

______if (!Number.isInteger(value)) {

________throw new TypeError('The age is not an integer');

______}

______if (value > 200) {

________throw new RangeError('The age seems invalid');

______}

____}

____// The default behavior to store the value

____obj[prop] = value;

____}

__};


let person = new Proxy({}, validator);

person.age = 100;

console.log(person.age);

// 100


person.age = 'young';

// 抛出异常: Uncaught TypeError: The age is not an integer


person.age = 300;

// 抛出异常: Uncaught RangeError: The age seems invalid

编辑于 2020-12-25 15:08:10 回复(0)