Js: keyword 'this'

What does this keyword refer to, and how to make it refer to what we want.

10 flashcards · Programming Languages · by lakesare

  1. What's the result? function hi() { console.log(this.a); } var first = hi.bind({ a: 'AAA' }); first(); //=> var second = first.bind({ a: 'BBB' }); second(); //=>

    'AAA' 'AAA' Because function can only be bound once! Second bind is ignored.

  2. How does this behave in arrow function?

    No matter what, arrow function's this is set to what it was when it was created. Their this is set to that of the outer execution context.

  3. What's the result? var object = { prop: 37 }; function independent() { this.prop; } object.b = { f: independent, prop: 42 }; object.b.f();

    //=> 42 It matters only that the function was invoked from object.b.f. When a function is called as a method of an object, its this is set to the object the method is called on.

  4. What is this in Js?

    this is the current execution context of a function.

  5. When a function is used as an event handler, its this is set to the element the event fired from.

    this === e.target

  6. In strict mode, what is this in function invocation (NOT method invocation)?

    undefined.

  7. What's the result? "use strict"; const numbers = { numberA: 5, numberB: 10, sum: function() { this; //=>... function calculate() { this; //=>... } return calculate(); } }; numbers.sum();

    numbers object undefined In strict mode, this is always undefined inside function invocation. And since calculate is called just like calculate(), not from any object, it is a function invocation.

  8. What's the result? "use strict"; const numbers = { sum: function() { console.log(this); //=>... } }; const hi = (someFunction) => { someFunction(); } hi(numbers.sum); How to fix it?

    undefined! Unfortunately the method is separated from its object when passed as a parameter. So it's like: const separatedSum = numbers.sum; setTimout(separatedSum); To rebound sum, we can: hi(numbers.sum.bind(numbers));

  9. .bind() makes a permanent context link and will always keep it.

    A bound function cannot change its linked context when using .call() or .apply() with a different context.

  10. Because the function invocation has the biggest impact on this, from now on do not ask yourself: Where is this taken from?

    but do ask yourself: How is the function invoked?For an arrow function ask yourself: What is this where the arrow function is defined?