Polyfill/fix for using dot notation on reserved JS words like 'function'

a 夏天 提交于 2019-12-24 08:37:08

问题


This question is a followup of this

Background:

var a = function(){ console.log("function is() initialized"); };

// assign a property named 'function' to function 'a'

a.function = function afunction(f){ return (typeof f === 'function'? true: false); };

// Use our is function to test if a given variable is a function

a.function(a); // IE throws 'expected identifier' error v/s Chrome correctly outputs "true"

Solution

Use bracket notation to avoid interference as described here i.e.

a["function"](a) instead of a.function(a)

Followup Question

Since the advanced browsers are able to "get around" calling a.function(a), is there a polyfill/fix available that supports using dot notation on reserved javascript words. After using this polyfill/fill, one should be able to continue using dot notation in older browsers(example IE 8) i.e.

allow using a.function(a) instead of a["function"](a)


回答1:


I'm fairly certain no such polyfill exists, because this difference in behaviors relies on a difference in JavaScript grammar, which determines how the lexical code is translated from a sequence of characters into a parse tree on instructions that can be executed.

The ECMAScript 3 grammar (which IE8 uses) allows dot-property-access with an Identifier after the dot, but the ECMAScript 5 grammar (which all mordern browsers use) allows the broader IdentifierName to follow the dot. The difference is significant because Identifier is defined as

IdentifierName but not ReservedWord

Thus, ECMAScript 3's disallowance of reserved words (like function) in dot-access expressions exists at a grammar level.

A polyfill that could correct this behavior in IE8 would need to change how the browser behaves at parse time, before the code even begins to run. Scripts have no capability to alter the behavior of the browser's JavaScript parser.

It's possible in theory to run your code through an ES5-to-ES3 compiler, which would automatically transform your a.function to a["function"]. Mascara is the only project I could find that might suit your needs, but it's important to note that it costs $980.



来源:https://stackoverflow.com/questions/25532175/polyfill-fix-for-using-dot-notation-on-reserved-js-words-like-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!