4

I have two pieces of code that each work as expected:

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

and

function Test() {}

(function() {
    console.log(this)
}).call(Test)

They both produce the expected output: [Function: Test].

However, when these independent code fragments are combined, it produces an error. So, running the following code

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

(function() {
    console.log(this)
}).call(Test)

results in

TypeError: tmp.call(...) is not a function

I found a non-elegant fix for this, which is adding a delay to the second code fragment. So, the following would produce the desired output ([Function: Test] twice):

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)

setTimeout(() => {
    (function() {
        console.log(this)
    }).call(Test)
}, 100);

The fact that the timeout seems to fix it makes me think it's related to some asynchronous stuff, but I can't explain exactly why it's happening.

0

2 Answers 2

9

You're falling victim to an automatic semicolon insertion trap. The code

tmp.call(Test)

(function() {
    console.log(this)
}).call(Test)

is interpreted as if it were written

tmp.call(Test)(function() { console.log(this) }).call(Test)

If a semicolon is introduced:

tmp.call(Test);

(function() {
    console.log(this)
}).call(Test)

then it will work.

The precise rules involve some "legalese" that's somewhat hard to digest, but the basic idea (in this case) is that a semicolon won't be inserted when an expression can syntactically work when the newline is considered to be a simple space character.

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, putting a semicolon fixes it
I'll never understand why people want to get rid of semicolons;
@zero298 Some JS code formatting standards clearly state that semicolons are not required and must be omitted. For example, standardjs.com/rules.html#semicolons.
@zero298 because some people keep switching between languages that do and don't use them, and JS doesn't even warn about the lack of semicolons.
I've got C, C++, and Java so firmly wired into my head that missing ; code makes me uncomfortable, but I'm happy for everyone to follow their heart in the matter. (Learning Erlang was really trippy.)
2

This is how your code snippet is interpreted:

function Test() {}

let tmp = function() {
    console.log(this)
}
tmp.call(Test)(function() {
    console.log(this)
}).call(Test)

To fix it, add a semi-colon after tmp.call(Test)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.