I am getting "Reference Error" very randomly (about once in 200 attempts ) with the following code.
var securityPrototype = {
init: function(){ /* ... */ },
encryptionKey: function x() {
var i = x.identifier;
return getKey(i);
}
}
securityPrototype.encryptionKey.identifier = Date.now();
function Security(){}
Security.prototype = securityPrototype;
Security.constructor = Security;
function getKey(){ /* ... */ }
var gate = new Security()
gate.encryptionKey(); // Randomly throws : ReferenceError: x is not defined
This code segment lives inside other code but no "eval" is being used , neither the 'with' operator.
I am trying to figure out if due to any condition it is possible to get this error here.
Browser that reproduces this: Chrome on Mac and Windows. IE and Safari work fine.
That's because a bug in the implementation of named function expressions, that exists in some versions of some browsers.
In those browsers, two separate function objects are created when you use a named function expression. The property gate.encryptionKey
is a reference to one function object, and the name x
is a reference to a different function object. They both contain the same code, but they are different instances of the Function
class.
When you assign a value to gate.encryptionKey.identifier
, that property is only available in the function object that gate.encryptionKey
references. The function object that x
references doesn't have that property.
Simple example of the behaviour in those browsers:
var f = function g(){};
f === g; // false
f.expando = 'foo';
g.expando; // undefined
This example (example #3) was taken from the page Named function expressions demystified, where you can read more about named function expressions, and the implementation bugs.