【问题标题】:How/where can I inspect JS methods' internal code? [duplicate]我如何/在哪里可以检查 JS 方法的内部代码? [复制]
【发布时间】:2020-06-11 16:23:55
【问题描述】:

例如,当我们将回调函数传递给Array.filter()

[1,2,3].filter(el => {
  return el === 2;
})

我想检查方法的内部结构,最后导致回调

【问题讨论】:

标签: javascript


【解决方案1】:

你不能,也许你最接近的方法是查看你最喜欢的 Javascript 解释器的源代码,或者你可以查看为某些方法提供的 polyfill 代码 - filter 是一个 - on MDN

例如

if (!Array.prototype.filter){
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();

    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;

    var kValue;
    if (thisArg === undefined){
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          kValue = t[i]; // in case t is changed in callback
          if (func(t[i], i, t)){
            res[c++] = kValue;
          }
        }
      }
    }
    else{
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          kValue = t[i];
          if (func.call(thisArg, t[i], i, t)){
            res[c++] = kValue;
          }
        }
      }
    }

    res.length = c; // shrink down array to proper size
    return res;
  };
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-02
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 2021-08-14
  • 2011-09-15
相关资源
最近更新 更多