js用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);
}

当我改变input2的值的时候。input1的value会发生变化,这是必然的。但是这时候我打印data。data值竟然也更新了。input2.onchange里 并没有调用data的set啊。input1.value发生改变,也并没有触发input1的onchange啊。那 data的数据的更新,到底是怎么触发的啊?


拉丁的传说
浏览 463回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript