What is importance of ‘this’ keyword in javascript?
- by admin
- 0
‘this’ always point to an object.
when a function executes inside an object , it gets the this property and its value.
alert(this); // will return object window, because it is executing in global object.
var person = {
firstName :”john”,
lastName :”johny”,
myname:function () {
alert(this); // will return person object beacuse myname function defined inside “person” object
console.log (this.firstName + ” ” + this.lastName);
}}
person.myname ();
alert(this); // will also return object window, beacuse of “this” has value only inside the function its is defined inside a object.
“this” is not assigned a value until an object invokes the function.
So if we declare a function in global scope this variable will point to the window object(global object)
firstName=”john”;
lastName=”johny”;
function myname() {
alert(this); // will return global object beacuse myname function defined inside global scope.
console.log (this.firstName + ” ” + this.lastName);
}
“window” is the object that all global variables and functions are defined on.
Reference: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
‘this’ always point to an object. when a function executes inside an object , it gets the this property and its value. alert(this); // will return object window, because it is executing in global object. var person = { firstName :”john”, lastName :”johny”, myname:function () { alert(this); // will return person object beacuse myname function…
‘this’ always point to an object. when a function executes inside an object , it gets the this property and its value. alert(this); // will return object window, because it is executing in global object. var person = { firstName :”john”, lastName :”johny”, myname:function () { alert(this); // will return person object beacuse myname function…