0

Had an interview. So I had interesting question about "what would console log output".(There might be a lot of people wondering the same stuff, I tried to read docs but no way, couldn't get)

It's a bit confusing, so I don't understand why link() outputs undefined and hero.getKek() => test. Odd behaviour isn't it ? link===hero.getKek. So these are the same functions, I would say, using "this" make function less controllable. Why Can't I create an alias for long chained nested object field, I HAVE to repeat the same chaining ? a.b.c.d.e.g() = > "test", alias() => "test" makes more sense. I can use call or apply to borrow context for link function, but that still doesn't have any logic for me

const hero={
    kek:'test',
    getKek:function (){
        console.log(this.test);
    }
}

const link=hero.getKek;
link(); // undefined (why?)
hero.getKek() // test
fake364
  • 99
  • 8
  • `const link = hero.getKek.bind(hero)` – SuperStormer Aug 30 '22 at 22:56
  • For regular functions, the value of `this` is determined by how you *call* a function, not how you create it. In the code `hero.getKek()`, the characters `hero.` are responsible for setting `this` to `hero`. If you don't have anything specifying what `this` is (as in the code `link()`), then `this` defaults to the window object (or undefined in strict mode). – Nicholas Tower Aug 30 '22 at 22:58
  • @SuperStormer yes! I know I can bind, why should I bind it? I would better ask "why js developers made us bind every time we want to create alias ? It should have been by deafult" – fake364 Aug 30 '22 at 22:58
  • Also relevant: https://en.wikipedia.org/wiki/Law_of_Demeter . If you have 5 dots in an expression (eg. `a.b.c.d.e.g()`), you're doing something wrong. – SuperStormer Aug 30 '22 at 22:59
  • The function becomes a `function constructor` of an object because you used `this`, so it replaces it self with an object ! – Yasser CHENIK Aug 30 '22 at 23:01
  • @YasserCHENIK No? Using `this` won't automatically make it a constructor??? – SuperStormer Aug 30 '22 at 23:03
  • @YasserCHENIK function works like a constructor when we call function with "new", and doesn't return any object – fake364 Aug 30 '22 at 23:04
  • @SuperStrmer , Here is an example from [this answer](https://stackoverflow.com/a/9822631/14629458) – Yasser CHENIK Aug 30 '22 at 23:06
  • It's only a constructor when you use `new`, as that answer clearly describes. – SuperStormer Aug 30 '22 at 23:17
  • @SuperStormer He's not in strict mode. This has nothing to do with anonymous functions, it has to do with whether you're calling the method through an object or not. – Barmar Aug 30 '22 at 23:37

0 Answers0