Determine if a function is called with null, undefined, or the global object in non-strict mode

Viewed 68

I am looking to throw a TypeError whenever a particular function in non-strict mode is called with null / undefined. There is a partial workaround by forcing the function to locally execute in strict mode, but it's an incomplete solution.

var t = function(s) { console.log(this) };
t.call(null), t.call(undefined); // window, window

(function() {
    "use strict";
    t = function(s) { console.log(this) }

    t.call(null), t.call(undefined); // null, undefined
})();

I also can't throw if this is window, as the function may be legitimately called with this as the global object. Is there a complete workaround not involving use strict?

1 Answers

It's not possible to get the original null or undefined thisArgument in a sloppy-mode function. You must wrap your function in a strict mode one.

Notice that not the strictness in the call location is important for this, but only the definition of your function. You want

function t() {
    "use strict";
//  ^^^^^^^^^^^^^
    console.log(this)
};

// calls in sloppy mode:
t(), t.call(null), t.call(undefined); // undefined, null, undefined

(function() {
    "use strict";
    // calls in strict mode:
    t(), t.call(null), t.call(undefined); // undefined, null, undefined
})();

Related