1.

Which event occurs when a value is added in an input box in JavaScript?

Answer»

JavaScript “this” keyword simply means that whatever scope you are inside, it belongs to that. Now the scope can be a function or and Object. Although, there are some exception to this RULE. We can have “this” in various context. Let’s go through them.

“this” in simple function
In a normal JS function like below, the “this” refers to global window object.

function foo() {   console.log(this);   console.log(this === window);   } foo();

Running the above code will give.

There is a special case with strict mode.

In strict mode “this” to be undefined , as global object refers to undefined instead of window object. 

function foo() {   'use strict';   console.log(this);   console.log(this === window);   } foo();

“this” in an object property
In an object which have a property as a function, the value of “this” is the Object itself.

var obj = {}; obj.foo = function() {   console.log("Inside obj foo");   console.log(this); } obj.foo();

this is Object itself

“this” with constructor function
When a function is called with “new” keyword, it is known as constructor function. And the value of “this” refers to the NEWLY created instance.

function PERSON(fn, ln) {  this.first_name = fn;  this.last_name = ln; this.displayName = function() {     console.log(`Name: ${this.first_name} ${this.last_name}`);     console.log(this);  } } let person = new Person("Tim", "Horton"); person.displayName();   let person2 = new Person("Mary", " POPPINS"); person2.displayName();

The newly created instance is nothing but an object, because everything in JS is an object.



Discussion

No Comment Found