麻烦理解mdn示例

时间:2019-12-15 10:43:08

标签: es6-proxy

我无法理解来自Proxy的es6代理示例。我的JavaScript知识有些不足。传教士叫过哪里?

操纵DOM节点

有时您想切换两个不同元素的属性或类名称。这是设置处理器的使用方法。

let view = new Proxy({ selected: null }, { set: function(obj, prop, newval)
    {
        let oldval = obj[prop];
        if (prop === 'selected') { 
            if (oldval) {
                oldval.setAttribute('aria-selected', 'false');
            } 
            if (newval) 
            { 
                newval.setAttribute('aria-selected', 'true');
            } 
        } // The default behavior to store the value 
        obj[prop] = newval; // Indicate success return true;
    } });
let i1 = view.selected = document.getElementById('item-1');
console.log(i1.getAttribute('aria-selected')); // 'true' 
let i2 = view.selected = document.getElementById('item-2'); 
console.log(i1.getAttribute('aria-selected')); // 'false'
console.log(i2.getAttribute('aria-selected')); // 'true'

0 个答案:

没有答案