2016-12-10 86 views
0

我一直在玩javascript Object.defineProperty來創建數據綁定。這裏是我的例子。我不明白爲什麼數據的屬性:名稱更新時,我更改html.Thx input2的值非常多。使用javascript Object.defineProperty創建數據綁定

<input type="text" id="text1" /> 
<input type="text" id="text2" /> 

var input1 = document.querySelector("#text1"); 
var input2 = document.querySelector("#text2"); 
var data = {}; 
Object.defineProperty(data, "name", { 
    configurable: true, 
    get: function(){ 
     console.log(1111); 
     return input1.value 
    }, 
    set: function(newValue){ 
     console.log(222); 
    input1.value = newValue; 
    input2.value = newValue; 
    } 
}) 
data.name = "sss"; 
input1.onchange = function(){ 
    console.log(33333) 
    data.name = data.name; 
} 
input2.onchange = function(){ 
    input1.value = this.value; 
    console.log(data); 
} 

回答

0
  1. 當用戶改變input2input2.onchange()被調用。
  2. input2.onchange()input1.value
  3. 由於get()方法返回input1.value,引用data.name返回新的input1.value