M
M
Mithgol2013-07-18 13:01:31
JavaScript
Mithgol, 2013-07-18 13:01:31

Is it possible to substitute constructors for values ​​generated by simple {} and [] constructs in JavaScript?

As you know, in the real application of the JavaScript language, the global object is not the only one: each browser window has its own global object and its own system of global constructors, which are its fields.
This is usually useful because using the Prototype library or other tool that adds to or replaces the prototype does not affect similar objects in other windows. Bugs don't spread too widely (multiple windows), malicious applications don't have the ability to inject into sensitive data structures, and so on.
However, this separation comes at a cost, and it can often be seen as redundant. In particular, a simple check for value instanceof Arrayis not useful for checking whether some passed value is an array if it was passed from another context in which another value is Array . (For more on this, see Determining with absolute accuracy whether or not ... , for example.)
One way to overcome this shortcoming is to create special functions, such as the Array.isArray method introduced in ECMAScript 5. This way , however, does not help in any way in changing the behavior of those source code libraries that were previously written without taking into account the possible difference in contexts and without using new ECMAScript functions.
The second way (perhaps even more obvious) is to replace the global objects of one context with the global objects of another context. Something like this:

  • Object = otherContext.Object;
     
  • Array = otherContext.Array;
     
  • etc…

Unfortunately, we have to see that the equivalences ({}).constructor === Object and [].constructor === Array are violated after such a replacement.
Is there a way to restore them so that the simple {…} and […] constructs continue to work, but produce objects and arrays of the borrowed context?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kxyu, 2013-07-18
@Mithgol

There is no such way:
http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.4
http://www.ecma-international.org/ecma-262/5.1/#sec-11.1 .5

A
Alexander Keith, 2013-07-18
@tenbits

Indirectly on the topic:
If you forward data into the frame through , then there should be no postMessageproblems with -x instanceof RegExp/Array

// top
frames.myframe.postMessage([ 'action', [], /x/ ], '*');

// myframe
window.onmessage = function(event){
   event.data[1] instanceof Array // -> true
   event.data[2] instanceof RegExp // -> true
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question