简体   繁体   English

Object.assign与NodeList

[英]Object.assign this with NodeList

I'm building a simple DOM utility library, similar to jQuery is ES6. 我正在构建一个简单的DOM实用程序库,类似于jQuery的ES6。

class jQuery {

    constructor(selector) {            
        let elements = document.querySelectorAll(selector);
        Object.assign(this, elements);
    }
}

let $ = selector => new jQuery(selector);

console.log($('h1'));

I'm trying to merge this with my elements, both types are objects but the results its just an empty object (this). 我正在尝试将其与我的元素合并,这两种类型都是对象,但是结果只是一个空对象(this)。

But, if I merge this with { foo: 'bar' } its working. 但是,如果我将this{ foo: 'bar' }合并,则可以正常工作。

Can someone explain me why this is happening? 有人可以解释一下为什么会这样吗?

Live at https://jsbin.com/zupece/edit?js,console,output 直播https://jsbin.com/zupece/edit?js控制台,输出

I think that NodeList does not support get the way you want it to, which is used by Object.assign . 我觉得NodeList不支持get它使用你想要的方式, Object.assign

You could just assign it as an composite: 您可以将其分配为组合:

class jQuery {

    constructor(selectorOrElement) {

        this.elements = selectorOrElement instanceof HTMLElement ? [selectorOrElement] : document.querySelectorAll(selector);
    }

    addClass(className) {

        this.elements.forEach(function (element) {

            element.classList.push(element);
        });
    }

    each(callback) {

        for (var i = 0; i < this.elements.length; i++) {

            var scope = this.elements[i];
            callback.call(scope, i, new jQuery(scope)); 
        }
    }
}

This is more OOP anyway. 无论如何,这是更多的OOP。 Besides, various JavaScript engines can now try to optimize your code for better performance. 此外,各种JavaScript引擎现在可以尝试优化您的代码以获得更好的性能。 This is much less possible while using Object.assign . 使用Object.assign这种可能性要小得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM