繁体   English   中英

为什么我需要从另一个来源指向Array构造函数,为什么我不能直接在数组对象上调用toString()?

[英]Why do I ever need to point the Array constructor from another source and why can't I call toString() directly on array objects?

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

var _Array = window.frames[window.frames.length-1].Array;

var arr = new _Array(1,2,3);

typeof arr; //'object'
arr instanceof Array; //false

我对此代码有3个问题:

  1. Object.prototype出现在_Array和Array原型的原型链上,但是Array和_Array不在同一链中,因此(Array的instance较旧)返回false?

  2. 我想了解这里到底发生了什么,这是我的想法:_Array指向与“ windows.iframe [...]。Array”所指向的构造函数相同的构造函数,然后我们创建_Array的实例,其原型指向Array。原型,并且Array.prototype.proto指向Object.prototype。 因此,_Array和Array都是数组对象的构造函数,它们是从Object.prototype继承的。 因此,为什么我需要直接从Object.prototype调用toString()才能在_Array和Array对象上获取“ [object Array]”? 当我这样调用时:arr.toString()我得到一个空字符串,当我调用Object.prototype.toString.call(arr)时得到“ [object Array]”。 这是为什么?

  3. 有人可以解释一下为什么我需要从另一个来源指向Array构造函数吗? 在此代码中,_Array指向与“ windows.iframe [...]。Array”所指向的构造函数相同的构造函数。 为什么有用?

Array 只是具有行为的数据结构。 有很多数组实现,您也可以实现自己的数组。

  1. 我想了解这里到底发生了什么...
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

// Accessing a new type of Array
var _Array =
  window.frames[window.frames.length-1].Array;

// Instantiates new array of type "_Array" (declared in iframe)
var arr = new _Array(1,2,3); // [1,2,3]

// Shows the type of arr variable
typeof arr; //-> 'object'

// Asserting that the "arr" instance is not in an instance of type "Array" (native Javascript type), rather it is of the type declared in the iframe
arr instanceof Array; //-> false
  1. (...)为什么有用?

请注意,此代码本身无用(这是一个示例片段),其可能的目标是显示

  • JavaScript中与类型相关的基本操作
  • iframe保留数据的可能性,例如新类型( Array

暂无
暂无

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

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