/**
* 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
});