this keyword is used to point at the current object in the code.
For instance: If the code is presently at an object created by the help of the ‘new’ keyword, then ‘this’ keyword will point to the object being created.
It has different values depending on where it is used:
- In a method,
thisrefers to the owner object. - Alone,
thisrefers to the global object. - In strict mode
thisrefer to the global object. - In a function,
thisrefers to the global object. - In a function, in strict mode,
thisisundefined.
In an object method, this refers to the current object.
In the example, this refers to the employee object.
this Alone
when this keyword is used alone, not written inside a function or object then it will refer to global object. & In browser window global object will be [object window]
In a browser window the Global object is [object Window]:
var x = this;
this in a Function (Default)
In a JavaScript function, the owner of the function is the default binding for this.
So, in a function, this refers to the Global object [object Window].
function empFunction() {
return this;
}
this in Strict mode
In strict mode this also refers to the Global object [object Window]:
Example
"use strict";
var x = this;
this in a Function (Strict)
in JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined.
Example
"use strict";
function empFunction() {
return this;
}
Comments
Post a Comment