What is the purpose of the 'this' keyword in javascript

Unlike another language, in JavaScript this always refers to the "owner" of the function that we are executing, or rather, to the object that is the function.

What is the advantage / purpose of this behavior compiled with other languages?

+4
source share
2 answers

Since you are allowed to set 'this', you can set the scope of any function that you call, which allows you to do some interesting things with function closures. That is how most JS frameworks allow you to do more natural object-oriented class behavior. This is especially useful when you have event listeners and want to set the scope of the listening function.

+3
source
  • By default, this applies to the global object.
  • When a function is called as a property of the parent object, it refers to the parent object inside this function.
  • When a function is called with a new operator, this refers to the newly created object inside this function.
  • When a function is invoked using a call or applied, this refers to the first argument passed for the call or application. If the first argument is null or not an object, this refers to the global object.

Taken from http://unschooled.org/2012/03/understanding-javascript-this/

Also learn this.

http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this

0
source

Source: https://habr.com/ru/post/1414254/


All Articles