ES6 系列之 defineProperty 与 proxy


/**
* ES6 系列之 defineProperty 与 proxy
*/

/**
* definePropety(obj,prop,descript)
* obj:定一个对象
* prop:定义对象属性
* descript:设置属性值值 // 数据绑定,数据监听
*/
var obj = {};
object. defineProperty( obj, num, {
value: 1, // 设置该属性的值
configurable: true, // 可以使用delete的属性
emumerable: true, // 可以使用枚举--for-in循环
writable: true, // 可以修改value的值
});
// 属性符描述符必须是数据描述符或者存储数据描述符二种形式,不能同时是二者
// 1
object. defineProperty({}, num, {
value: 1,
configurable: true,
emumerable: true,
writable: true,
});
// 2
var value = 1;
object. defineProperty({}, num, {
get : function ( value) {
return value;
},
set : function ( newvalue) {
return newvalue;
},
emumerable: true,
writable: true,
})

// 监听对象的问题
function Archiver() {
var value = null;
var Archiver = [];
Object. defineProperty( this, num, {
get : function () {
console. log( '执行了 get 操作');
return value;
},
set : function ( value) {
console. log( '执行了set 操作');
value = value;
Archiver. push({ val: value });
}
});

this. getArchiver = function () {
return Archiver;
}
}

var src = new Archiver();
src. num //执行了 get 操作
src, num = 11;
src. num = 12;
console. log( src. getArchiver());
// watchAPI, 即当数据变化的时候,自动进行数据渲染
var obj = {
value: 1
}

// 储存 obj.value 的值
// var value = 1; // 更新变量使用set方法

Object. defineProperty( obj, "value", {
get : function () {
console. log( 'gun');
return value;
},
set : function ( newValue) {
console. log( 'hundan');
value = newValue;
document. getElementById( 'container'). innerHTML = newValue;
}
});

document. getElementById( 'button'). addEventListener( "click", function () {
obj. value += 1;
});

/**
* 重新封装的一个watch
*
*/

( function () {
var root = this;
var obj = {
value: 1
};
watch( obj, "value", function ( newvalue) {
document. getElementById( 'container'). innerHTML = newvalue;
});
document. getElementById( 'button'). addEventListener( 'click', function () {
obj. value += 1;
});
function watch( obj, name, func) {
var value = obj[ name];
Object. defineProperty( obj, name, {
get : function () {
return value
},
set : function ( newvalue) {
value = newvalue;
func( value);
}
})
console. log( 'valuevaluevaluevalue===' + obj. value);
}

})();
/**
* proxy 就必须修改代理对象,即 Proxy 的实例才可以触发拦截。
*
*/
( function () {
var root = this;

function watch( target, func) {

var proxy = new Proxy( target, {
get : function ( target, prop) {
return target[ prop];
},
set : function ( target, prop, value) {
target[ prop] = value;
func( prop, value);
}
});

if ( target[ name]) proxy[ name] = value;
return proxy;
}

this. watch = watch;
})()

var obj = {
value: 1
}

var newObj = watch( obj, function ( key, newvalue) {
if ( key == 'value') document. getElementById( 'container'). innerHTML = newvalue;
})

document. getElementById( 'button'). addEventListener( "click", function () {
newObj. value += 1
});


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM