polyfill-service: this === undefined when polyfills are wrapped in an IIFE containing `use strict`
Explanation
(function () {
'use strict';
(function (global) {
function Promise () {
// ...
}
global.Promise = Promise; // Uncaught TypeError: Cannot set property 'Promise' of undefined
}(this));
}())
Problem files
➜ git grep --name-only '[}|)](this)' -- polyfills/*polyfill.js
polyfills/Event.hashchange/polyfill.js
polyfills/JSON/polyfill.js
polyfills/Navigator.prototype.geolocation/polyfill.js
polyfills/Promise/polyfill.js
polyfills/URL/polyfill.js
polyfills/atob/polyfill.js
polyfills/devicePixelRatio/polyfill.js
polyfills/document.querySelector/polyfill.js
polyfills/getComputedStyle/polyfill.js
polyfills/localStorage/polyfill.js
polyfills/matchMedia/polyfill.js
polyfills/performance.now/polyfill.js
polyfills/requestAnimationFrame/polyfill.js
polyfills/viewport/polyfill.js
15 polyfills does not work as expected
About this issue
- Original URL
- State: closed
- Created 12 years ago
- Comments: 20 (20 by maintainers)
Commits related to this issue
- Better IIFE, fixes #352 — committed to polyfillpolyfill/polyfill-service by triblondon 12 years ago
OK, how about:
I’ve tested this and it seems to work. window will not throw a referenceerror if used with typeof, and then inside the IIFE we can redefine
windowandselfto be equal tothis. That gives us the most flexible options for supporting third party polyfill code which might be assigning into properties ofwindow,selforthis, it’s compatible with web workers, while still being able to cope with environments in which the developer has redefinedselforthis.I believe the justification for the use of the
}(this));pattern is that the polyfills may be loaded in a worker rather than a window. We don’t want to stop the polyfills from working in a web worker. I agree with Juan, if the polyfill wanted to set use strict, it could do so, but the reason use strict works in the way it does is to avoid breaking the web for code that already exists and would stop working if the stricter rules of use strict were applied.I don’t have any objection to
Function('return this')()if that works in everything above our baseline, however, you usedPromiseas your example use case, and that’s interesting because we are simply copying the source of the promise polyfill from the third party repo, which uses the}(this));pattern, so we don’t have control over the use of the pattern there.Potentially the easiest and cleanest solution would be to add a definition of
thisat the top of the closure that we output when we generate the polyfill bundle:This will solve your problem provided that you generate your autopolyfiller bundle by using the service API rather than simply reading the polyfill source files individually. That would probably be a good idea anyway, since it would enable you to easily output a polyfill service CDN URL from autopolyfiller rather than a one-size-fits-all bundle.