JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
JavaScript has many useful reserved keywords. I will walk you through usage and benefits of these keywords
Delete keyword
When we work on large applications then we work with many objects. We are familiar with problems like memory leak, performance of application is not good, and similar issues arise at a later stage. I always recommend that we know how much memory we are consuming in our application.
Ex- Chrome provides a quick way to look into memory usage,
The main advantage is to delete unwanted property from object,
- var automobile = {engine: true, fuel: true, tyres:2 };
- var car = Object.create (automobile);
- console.log (car.tyres);
-
- car.tyres = 4;
Q: We have deleted tyres from car object, what will happen if we print car.tyres?
Ans: The output of below statement will be 2 because it refer tyres property in automobile object,
- console.log (car.tyres);
-
- To delete tyres completely remove from automobile object
-
- delete automobile.tyres;
- console.log (automobile.tyres);
This keyword
“this” is not a variable. It is a keyword. You cannot change the value of this. It refers to the global object in all global code.
We know to create multiple objects we can use Object Constructor function. We’ll use this keyword to create property which belong to function,
- function Automobile (engine, fuel, tyres)
- {
- this.engine = engine;
- this.fuel = fuel;
- this.tyres = tyres;
- }
- var car =new Automobile (true, true , 4);
- var bike =new Automobile (true, true , 2);
Second example, this refers to the parent object in the body of the function,
- var counter = {
- val: 0,
- increment: function () {
- this.val += 1;
- }
- };
- counter.increment();
- console.log(counter.val);
- counter['increment']();
- console.log(counter.val);
New operator
The new operator creates a new object. Any JavaScript function can be used as a constructor function with new.
Example- function F1 (val) {
- this.val = val;
- }
- var f = new F1("Foo");
- console.log(f.val);
- console.log(this.val);
-
- If we call f without new then this will refer to the global object (which is ex Windows )
- function F1 (val) {
- this.val = val;
- }
- var f = F1("Foo");
- console.log(this.val);
Summary
Rules are simple just we need awareness how to use delete, this, and new. Please share comments and feedback.
Read more articles on JavaScript: