Object.defineProperty 及 实现数据双向绑定

Object.defineProperty 及 实现数据双向绑定

韩小韩
2021-06-13 / 0 评论 / 273 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年06月13日,已超过1019天没有更新,若内容或图片失效,请留言反馈。

示例代码

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Object.defineProperty 及 实现数据双向绑定</title>
    <input type="text">
    <h1></h1>
</head>

<body>
    <script>
        const ipt = document.querySelector('input');
        const h = document.querySelector('h1');
        let hanObj = {
            name: '',
            _name: ''
        };
        Object.defineProperty(hanObj, 'name', {
            get() {
                return hanObj._name;
            },
            set(sval) {
                hanObj._name = sval
                h.innerHTML = sval
                ipt.value = sval
            }
        })
        ipt.oninput = function () {
            hanObj.name = this.value
        }
    </script>
</body>

</html>
0

评论 (0)

取消