JS – this keyword
“this” serves as an identity function, providing our neighborhoods a way of referring to themselves.
Easy Sample:
var person = { firstName :"Penelope", lastName :"Barrymore", // Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object, // "this" will have the value of the person object because the person object will invoke showFullName () showFullName:function () { console.log (this.firstName + " " + this.lastName); } } person.showFullName (); // Penelope Barrymore
Rhe result is:
Penelope Barrymore
Calling an Object’s Method:
<script type="text/javascript"> var deep_thought = { the_answer: 42, ask_question: function () { return this.the_answer; } }; var the_meaning = deep_thought.ask_question(); </script>
Returning the value stored in this.the_answer: 42.
Constructor:
<script type="text/javascript"> function BigComputer(answer) { this.the_answer = answer; this.ask_question = function () { return this.the_answer; } } var deep_thought = new BigComputer(42); var the_meaning = deep_thought.ask_question(); </script>
Instead of explicitly creating the deep_thought object, we’ll write a function to create BigComputer objects, and instantiate deep_thought as an instance variable via the new keyword. When new BigComputer() is executed, a completely new object is created transparently in the background. BigComputer is called, and its this keyword is set to reference that new object. The function can set properties and methods on this, which is transparently returned at the end of BigComputer’s execution.
References:
– http://www.digital-web.com/articles/scope_in_javascript/
– http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/