this Keyword
The 'this' keyword is a variable that is automatically set for you when a function is invoked.
Exactly what this value is depends on how the function is invoked.
This Owner is the Window
var a = function() {
alert(this);
}
a(); // Object Window
This Owner is the Object
var obj = {
property1 : "text",
method1 : function() {
alert(this.property1);
}
}
obj.method1(); // text
By default the scope of the "this" object is global
The window object is the global/top level object in the context of a browser.
The "this" object refers to the object that is executing the current line of javascript code.
If we are in "strict mode" then the default value of the "this" object is undefined.
Explicit Binding
This is also called "explicit binding of this keyword".
We can use the "call" method when calling a function, to pass in an object for "this".
var name = "solutions";
var obj = { name : "better" };
function myfunc() {
console.log(this.name);
}
myfunc.call(obj); // better
Implicit Binding
This is called "implicit binding of this keyword".
When an object property is called as a method, then that object becomes the default value of "this".
var name = "solutions";
var obj1 = {
name : "better",
prop1 : function() {
console.log(this.name);
};
}
var obj2 = {
name : "website",
prop1 : obj1.name
};
obj1.prop1(); // better
obj2.prop2(); // website
Default Binding
var name = "solutions";
function myfunc() {
var name = "better";
console.log(this.name);
}
myfunc(); // solutions
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext