确定在非严格模式下是否使用 null、undefined 或全局对象调用函数

Kit*_*aya 5 javascript

每当使用/TypeError调用非严格模式下的特定函数时,我都会抛出 a 。有一个部分解决方法是强制函数在严格模式下本地执行,但这是一个不完整的解决方案。nullundefined

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
})();
Run Code Online (Sandbox Code Playgroud)

我也不能抛出 if thisis ,因为该函数可以作为全局对象window合法地调用。this有没有不涉及的完整解决方法use strict?

Ber*_*rgi 2

在草率模式函数中不可能获取原始参数null或thisArgument 。undefined您必须将函数包装在严格模式一中。

请注意,对此重要的不是调用位置的严格性,而是函数的定义。你要

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
})();
Run Code Online (Sandbox Code Playgroud)