Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are parentheses ignored if they only contain a property accessor? [duplicate]

Given the following code, why doesn't (obj.foo)() receive window as this? It seems to me like the parentheses are ignored, rather than treated as an expression that evaluates to foo?

window.bar = 'window';
const obj = { bar: 'obj' };

obj.foo = function() {
  console.log(`Called through ${this.bar}`);
}

obj.foo(); // Called through obj

(obj.foo)(); // Called through obj - Why?

(0, obj.foo)(); // Called through window

(true && obj.foo)(); // Called through window
like image 755
nik10110 Avatar asked Nov 21 '19 08:11

nik10110


People also ask

What are the rules for parentheses and open brackets?

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. s consists of parentheses only ' () [] {}'. An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.

What are valid parentheses in a string?

Valid Parentheses. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

What is a set of parenthesis that are duplicate?

A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis.

How do you find redundant parenthesis in a counter?

If the number of characters encountered between the opening and closing parenthesis pair, which is equal to the value of the counter, is less than 1, then a pair of duplicate parenthesis is found else there is no occurrence of redundant parenthesis pairs. For example, ( ( (a+b))+c) has duplicate brackets around “a+b”.


2 Answers

They're not ignored, but the result of (obj.foo) is the same Reference (specification term) as the result of obj.foo (see this section in the spec). So the property accessor has the same information to work with to get the object and property and to use that object as this.

like image 181
T.J. Crowder Avatar answered Nov 04 '22 01:11

T.J. Crowder


Cause obj.foo evaluates to a Reference that contains obj and "foo". When you [[Call]] the reference, both obj and foo are known as part of the Reference.

Most operators (including the comma operator) evaluate the Reference to a value.

like image 20
Jonas Wilms Avatar answered Nov 04 '22 00:11

Jonas Wilms