js怎么查看一些方法的实现源代码 比如数组的push()方法

js怎么查看一些方法的实现源代码 比如数组的push()方法 可以查看到吗

阅读 12.6k
3 个回答

Just for fun :)

V8:
https://github.com/v8/v8/blob/master/src/js/array.js

// Appends the arguments to the end of the array and returns the new
// length of the array. See ECMA-262, section 15.4.4.7.
function ArrayPush() {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.push");

  if (%IsObserved(this))
    return ObservedArrayPush.apply(this, arguments);

  var array = TO_OBJECT(this);
  var n = TO_LENGTH_OR_UINT32(array.length);
  var m = %_ArgumentsLength();

  // It appears that there is no enforced, absolute limit on the number of
  // arguments, but it would surely blow the stack to use 2**30 or more.
  // To avoid integer overflow, do the comparison to the max safe integer
  // after subtracting 2**30 from both sides. (2**31 would seem like a
  // natural value, but it is negative in JS, and 2**32 is 1.)
  if (m > (1 << 30) || (n - (1 << 30)) + m > kMaxSafeInteger - (1 << 30)) {
    throw MakeTypeError(kPushPastSafeLength, m, n);
  }

  for (var i = 0; i < m; i++) {
    array[i+n] = %_Arguments(i);
  }

  var new_length = n + m;
  array.length = new_length;
  return new_length;
}

原生实现的方法看不了的~~~

不同的JavaScript引擎实现是不同的,而且可能是不同语言写的。

不过,对于Chrome浏览器或者Node.js,它们用的v8,你可以看这里:

https://github.com/v8/v8

首先声明,我没有看过。不过我找到了这个目录,里面有一些是用JavaScript写的:

https://github.com/v8/v8/tree/master/src/js

你可以去研究一下。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题