python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
check null values in JavaScript

What is ‘this’ in JavaScript?

Hello everyone, today's I am going to share a basic and very confusing concepts that is called 'this' keyword :)
The 'this' keyword behaves a little differently in JavaScript compared to other languages.
In most of the other languages, 'this' keyword is a reference to the current object instantiated by the classes and methods. 
In the JavaScript languages, 'this' keyword refers to the object which 'owns' the method, but it depends on how a function is called.
The examples in details as given below.
//Global Scope in JavaScript
//In the below example, ‘this’ keyword refers to the global object.

window.sms = "Hi, I am window object";

console.log(window.sms);
console.log(this.sms); // Hi, I am window object.
console.log(window === this); // Its return true.

//Calling a Function in JavaScript 
//In the below example, ‘this’ keyword remains the global object if we are calling a function.

window.sms = "Hi, I am window object";

// Creating a function
function thisMethod() {
    console.log(this.sms); // Hi, I am window object.
    console.log(window === this); //Its return true.
}

// Calling a function
thisMethod();

//Calling Object Methods in JavaScript
//In the below example, when we calling an object constructor or any of its methods, 
//‘this’ keyword refers to the instance of the object.

window.sms = "Hi, I am window object";

function objectTestMethod() {
    this.sms = "Hi, I am a test object.";
    this.method1 = function () {
        console.log(this.sms); // Hi, I am a test object.
    };
}

objectTestMethod.prototype. method2 = function () {
    console.log(this.sms); // Hi, I am a test object.
};

// Creating object and calling methods

var v = new objectTestMethod();
v. method1();
v. method2();

ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions