Javascript-this
The this keyword is one of the most widely used and yet confusing keywords in JavaScript(a variable that refers to the current object.). Here, you will learn everything about this keyword.
Example:
<script>
var address=
{
company:"I2tutorials",
city:"Hyderabad",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};
var fetch=address.fullAddress();
document.writeln(fetch);
</script>
OUTPUT:
I2tutorials Hyderabad UP
The following ways can be used to know which object is referred to by this keyword.
Global Context:
variables are declared outside the function.
<script>
var website="I2tutorials";
function web()
{
document.write(this.website);
}
web();
</script>
The call() and apply() method:
return a method that can be used on various objects.
<script>
var emp_address = {
fullAddress: function() {
return this.company + " " + this.city+" "+this.state;
}
}
var address = {
company:"i2tutorials",
city:"Hyderabad",
state:"UP",
}
The bind() Method:
The bind() method was introduced in ECMAScript 5. It provides a new function whose “this” keyword refers to the provided value, with a given sequence of arguments.
<script>
var lang="Java";
function lang_name(call)
{
call();
};
var obj={
lang:"JavaScript",
language:function()
{
document.writeln(this.lang+ " is a popular programming language.");
}
};
lang_name(obj.language);
lang_name(obj.language.bind(obj));
</script>
document.writeln(emp_address.fullAddress.call(address));
document.writeln(emp_address.fullAddress.apply(address));</script>