0

Now I'm studying about this keyword in Javascript reading Dmitry's article.

http://dmitrysoshnikov.com/ecmascript/chapter-3-this/#function-call-and-non-reference-type

In here, he shows a example.

var foo = {
  bar: function () {
    console.log(this);
  }
};

foo.bar(); // Reference, OK => foo
(foo.bar)(); // Reference, OK => foo

(foo.bar = foo.bar)(); // global?
(false || foo.bar)(); // global?
(foo.bar, foo.bar)(); // global?

I understand about Reference, and also can understand foo.bar().
Here are my questions.

  1. foo.bar() and (foo.bar)()
    Are these two different? I think, parenthesis which wrapping a expression could be omitted by interpreter. I can't catch the focus about this line. I mean, why he added // global? comment beside this line?

  2. (foo.bar = foo.bar)()
    In this line, I think the expression inside of parenthesis runs first, so put foo.bar to foo.bar recursively, and call the function foo.bar. right? Then, this going to be foo of course. I don't know why he use this code for example. I mean, why he added // global? comment beside this line?

  3. (false || foo.bar)()
    In here, first runs logical operator, thanks for parenthesis, and then this equals to (foo.bar)(). right? Then, this going to be foo of course. why he added // global? comment beside this line?

  4. (foo.bar, foo.bar)()
    In this line, I can't understand the code. What is the result of (function, function)? and what does this meaning?

I can try this code on jsfiddle and check the result.

https://jsfiddle.net/doingnone/3nksxwtd/4/

But I can't understand why he wrote these to show example for "Function call and non-Reference type". This is subtitle of this article.

AutumnSky
  • 279
  • 1
  • 13
  • In 2 and 3 `this` will not be `foo`. That is what he is explaining and the duplicate I linked also explains. 4 is basically the same but uses a comma operator, which I added a separate link for. – Paul Feb 21 '19 at 02:28
  • if you run the code, you will see only the first two `foo.bar` calls reference `this` as `foo`. The other three will reference `this` as `window` global object. – yqlim Feb 21 '19 at 02:28
  • @YongQuan Thank you I missed that point cause I confused. Yes I can see the difference of console.log for global and foo now. I keep trying to understand about dmitry's article. – AutumnSky Feb 21 '19 at 02:41

0 Answers0