为什么AngularJS在其isArray函数中不使用instanceof? [英] Why does AngularJS not use instanceof in its isArray function?

查看:82
本文介绍了为什么AngularJS在其isArray函数中不使用instanceof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从AngularJS isArray 来源:

From AngularJS isArray source:

return toString.call(value) === '[object Array]';

他们为什么不去?

return value instanceof Array;

推荐答案

因为如果您从其他 window (例如,另一个框架或iframe,子窗口,父窗口,等等),它不会是您的窗口中的 instanceof Array 构造函数.

Because if you receive an array from a different window (e.g., another frame or iframe, a child window, a parent window, etc.), it won't be instanceof the Array constructor in your window.

这就是为什么他们在ES5中添加了 Array.isArray 函数转换为JavaScript,因此我们可以停止以困难的方式进行操作,如下所示:

This is why in ES5 they added the Array.isArray function to JavaScript, so we could stop doing it the hard way, which looks like this:

if (Object.prototype.toString.call(theArray) === "[object Array]") ...

各个方面的示例:实时复制

父窗口:

<body>
  <input type="button" value="Click To Open Window">
<script>
  (function() {
    "use strict";

    var wnd;

    document.querySelector("input").onclick = function() {
      wnd = window.open("http://jsbin.com/yimug/1");
      display("Opened, waiting for child window to load...");
      setTimeout(waitForChild, 10);
    };

    function waitForChild() {
      if (wnd && wnd.sendMeSomething) {
        display("Child window loaded, sending [1, 2, 3]");
        wnd.sendMeSomething([1, 2, 3]);
      }
    }

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>

子窗口:

<script>
  (function() {
    "use strict";

    window.sendMeSomething = function(something) {
      display("Got " + something.join(", "));
      display("something instanceof Array? " + (something instanceof Array));
      display("Object.prototype.toString.call(something): " + Object.prototype.toString.call(something));
      if (Array.isArray) {
        display("Array.isArray(something)? " + Array.isArray(something));
      }
    };
    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>

输出(在子窗口中)( something 是从父级接收数组的参数的名称)

Output (in child window) (something is the name of the argument where it receives an array from the parent):


Got 1, 2, 3
something instanceof Array? false
Object.prototype.toString.call(something): [object Array]
Array.isArray(something)? true

这篇关于为什么AngularJS在其isArray函数中不使用instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆