TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

JavaScript This Keyword

JavaScript This Keyword with javascript, innerhtml, tutorials, examples, html, dom, css, tags, events, validation, object, loop, array, document etc.

<< Back to JAVASCRIPT

JavaScript this keyword

The this keyword is a reference variable that refers to the current object. Here, we will learn about this keyword with help of different examples.

JavaScript this Keyword Example

Let's see a simple example of this keyword.

<script>
var address=
{
company:"TheDeveloperBlog",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};


var fetch=address.fullAddress();
document.writeln(fetch);

</script>

Output:

TheDeveloperBlog Noida UP

The following ways can be used to know which object is referred by this keyword.

Global Context

In global context, variables are declared outside the function. Here, this keyword refers to the window object.

<script>
var website="TheDeveloperBlog";
function web()
{
document.write(this.website);
}
web();
</script>

The call() and apply() method

The call() and apply() method allows us to write a method that can be used on different objects.

<script>
var emp_address = {
    fullAddress: function() {
        return this.company + " " + this.city+" "+this.state;
    }
}
var address = {
    company:"TheDeveloperBlog",
    city:"Noida",
    state:"UP",

}

document.writeln(emp_address.fullAddress.call(address)); 
document.writeln(emp_address.fullAddress.apply(address));</script>

The bind() Method

The bind() method was introduced in ECMAScript 5. It creates 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>





Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf