题解 | #双向绑定#

双向绑定

https://www.nowcoder.com/practice/d1452ec52a134b328f23b97c02b230bd

function defineProperty(person, key, val) {
  Object.defineProperty(person, key, {
    get: function () {
      return val
    },
    set: function (newVal) {
      if (val !== newVal) {
        val = newVal;
        _render(ul);
      };
    }
  })
}

for (let key in person) {
  defineProperty(person, key, person[key])
}

inp.oninput = function () {
  person.weight = inp.value
}

此处最需要注意的是直接使用Object.defineproperty设置监听对象是get()的栈溢出问题,使用闭包处理一下即可

ps:严格来说还需要判断下person的是否为对象,此处没作处理

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务