this Keyword In a javascript
Printing ‘this’ in the global scope
console.log(this);
Window {window: Window, self: Window, document: document,, location: Location, …}
The ‘this’ keyword refers to the window object in the global scope.
Printing ‘this’ inside a function
e.g 1
function demo()
{
this.name="xyz";
console.log(this);
}
demo();
demo() is being called in the global scope, therefore the value of ‘this’ inside demo() becomes the window object.
output:
Window {window: Window, self: Window, document: document, name: 'xyz', location: Location, …}
e.g 2
The demo() function is being called using the ‘new’ keyword, therefore the value of ‘this’ inside demo() becomes a reference to a newly created object which contains the function object.
function demo()
{
this.name="xyz";
console.log(this);
}
new demo();
output:
demo {name: 'xyz'}
demo {name: 'xyz'}
New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with ‘new’ operator, the following actions are taken:
- A new empty object is created.
- The new object’s internal ‘Prototype’ property (__proto__) is set the same as the prototype of the constructing function.
- The ‘this’ variable is made to point to the newly created object. It binds the property which is declared with ‘this’ keyword to the new object.
- About the returned value, there are three situations below.
- If the constructor function returns a non-primitive value (Object, array, etc), the constructor function still returns that value. Which means the new operator won’t change the returned value.
- If the constructor function returns nothing, ‘this’ is return;
- If the constructor function returns a primitive value, it will be ignored, and ‘this’ is returned.
Syntax:
new constructorFunction(arguments)
Parameters:
- ConstructorFunction: A class or function that specifies the type of the object instance.
- Arguments: A list of values that the constructor will be called with.
Comments
Post a Comment