From c66b2818562a4480d37ba752963a00f1d263eb7a Mon Sep 17 00:00:00 2001 From: Ryan Chandler Date: Fri, 4 Jun 2021 11:52:20 +0100 Subject: LibJS: Fix functions binding this to global object in strict mode This fixes an issue where this would be bound to the global object by default when operating in strict mode. According to the specification, the expected value for |this| when no binding is provided is undefined. --- Userland/Libraries/LibJS/AST.cpp | 6 ++++++ Userland/Libraries/LibJS/Tests/functions/function-strict-mode.js | 9 +++++++++ 2 files changed, 15 insertions(+) (limited to 'Userland') diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index 1c2f0809b9..9e7edf8a40 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -158,6 +158,12 @@ CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interprete return { this_value, callee }; } + + if (interpreter.vm().in_strict_mode()) { + // If we are in strict mode, |this| should never be bound to global object by default. + return { js_undefined(), m_callee->execute(interpreter, global_object) }; + } + return { &global_object, m_callee->execute(interpreter, global_object) }; } diff --git a/Userland/Libraries/LibJS/Tests/functions/function-strict-mode.js b/Userland/Libraries/LibJS/Tests/functions/function-strict-mode.js index 99ec10b9a7..cf06b891a2 100644 --- a/Userland/Libraries/LibJS/Tests/functions/function-strict-mode.js +++ b/Userland/Libraries/LibJS/Tests/functions/function-strict-mode.js @@ -58,3 +58,12 @@ test('only the string "use strict" yields strict mode code', () => { "use stric"; expect(isStrictMode()).toBeFalse(); }); + +test("strict mode does not apply global object to |this|", () => { + "use strict"; + let functionThis; + (function () { + functionThis = this; + })(); + expect(functionThis).toBeUndefined(); +}); -- cgit v1.2.3