谁能帮我理解这一点?原型对象中的JavaScript'splice'方法

时间:2018-11-09 11:20:15

标签: javascript

有人可以帮助我理解吗?当我在原型方法中使用“ splice”时,控制台日志中显示的结果为“ select [div#index]”而不显示“ splice”,这看起来像“ select {0:div#index,length:1}”。

 select.prototype = {
         splice: function () {
         [].splice.apply(this, arguments);
     },
 }

照片:

Result 1:

Result 2 without 'splice':

脚本:

(function () {
    var doc = document;

    // it is for the test
    function select(sel) {

        if (sel) { this.push(query(sel)); }
        return this;
    }

    function query(selector) {
        let elems = [];
        var el = doc.querySelectorAll(selector);

            for (let i = el.length; i--; elems.unshift(el[i])) { }; 
        return elems;
    }

    select.prototype = {
        length: 0,

        push: function (elems) {
            [].push.apply(this, elems);
            return this;
        },
        // THIS METHOD
         splice: function () {
             [].splice.apply(this, arguments);
        },   

    };

    window['Q'] = function(selector) {
        return new select(selector);
    }

  console.log(window);
})();

Q("#index")以显示结果

1 个答案:

答案 0 :(得分:0)

它在select对象而不是数组上使用Array.prototype.splice函数。很好,splice(和其他几个数组函数)是有意通用的。只要它看到的对象this具有length并使用数字字符串命名的属性(就像数组一样),它将起作用。

值得一提的是,它使用的splice方式过于复杂,(效率非常低下)效率低下(它创建并丢弃了一个完全无意义的数组),并且没有t像数组上的splice一样返回删除的元素(因为它不返回Array.prototype.splice的返回值)。这个:

splice: function () {
     [].splice.apply(this, arguments);
},

应该简单地是:

splice: Array.prototype.splice

示例:

(function () {
    var doc = document;

    // it is for the test
    function select(sel) {

        if (sel) { this.push(query(sel)); }
        return this;
    }

    function query(selector) {
        let elems = [];
        var el = doc.querySelectorAll(selector);

            for (let i = el.length; i--; elems.unshift(el[i])) { }; 
        return elems;
    }

    select.prototype = {
        length: 0,

        push: function (elems) {
            [].push.apply(this, elems);
            return this;
        },
        /*
        splice: function () {
             [].splice.apply(this, arguments);
        },
        */
        splice: Array.prototype.splice

    };

    window['Q'] = function(selector) {
        return new select(selector);
    }

})();

const x = Q(".foo");
x.splice(0, 3);
for (let n = 0; n < x.length; ++n) {
  console.log(x[n].textContent);
}
<div class="foo">1</div>
<div class="foo">2</div>
<div class="foo">3</div>
<div class="foo">4</div>
<div class="foo">5</div>
<div class="foo">6</div>