1. // html
    2. <span id="box">
    3. <h1 id='text'></h1>
    4. <input type="text" id='input' oninput="inputChange(event)" />
    5. <button id="button" onclick="clickChange()">Click me</button>
    6. </span>
    7. const input = document.getElementById('input');
    8. const text = document.getElementById('text');
    9. const button = document.getElementById('button');
    10. const data = {
    11. value: ''
    12. }
    13. // 使用defineProperty
    14. function defineProperty(obj, attr) {
    15. let val
    16. Object.defineProperty(obj, attr, {
    17. set(newValue) {
    18. if (val === newValue) {
    19. return;
    20. }
    21. val = newValue;
    22. input.value = newValue;
    23. text.innerHTML = newValue;
    24. },
    25. get() {
    26. return val
    27. }
    28. })
    29. }
    30. defineProperty(data, 'value')
    31. function inputChange(event) {
    32. data.value = event.target.value
    33. }
    34. function clickChange() {
    35. data.value = 'hello'
    36. }
    37. // 使用proxy
    38. let handler = {
    39. get: function (obj, name) {
    40. return name in obj ? obj[name] : '';
    41. },
    42. set: function (obj, name, value) {
    43. obj[name] = value;
    44. text.innerHTML = value;
    45. input.value = value;
    46. },
    47. };
    48. let p = new Proxy(data, handler);
    49. function inputChange(event) {
    50. p.value = event.target.value
    51. }
    52. function clickChange() {
    53. p.value = 'hello'
    54. }