Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of 'this' keyword in Javascript [closed]

Tags:

javascript

Differently from the other language, in JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

What is the advantage/purpose of this behaviour compered with other languages?

like image 795
Lorraine Bernard Avatar asked Oct 07 '22 18:10

Lorraine Bernard


2 Answers

  • By default, this refers to the global object.
  • When a function is called as a property on a parent object, this refers to the parent object inside that function.
  • When a function is called with the new operator, this refers to the newly created object inside that function.
  • When a function is called using call or apply, this refers to the first argument passed to call or apply. 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 look into this as well.

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

like image 45
Larry Battle Avatar answered Oct 10 '22 08:10

Larry Battle


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

like image 121
netfire Avatar answered Oct 10 '22 09:10

netfire