This keyword
'this' keyword refers to the owner object.
- when we use this keyword alone it refers to the window object.
eg. console.log(this);
- In normal function, this refers the global object (window object).
eg.
<script>
function video(){
this.title = "Roar"; //Here title belong to window
this.length = 3.4;
}
let v = new video();
console.log(`Title : ${v.title} , Length : ${v.length}`);
//here we try to access variables of video function
</script>
- In a method, It refers the the parent object.
<script>
let book = {
title: "programming in js",
author : "abcd",
publisher : "forouzan",
displayDetail : function(){
console.log(`title : ${this.title},
author : ${this.author}, publisher : ${this.publisher}`);
console.log(this); // Now this refers book object
}
};
book.displayDetail();
</script>
output: title : programming in js, author : abcd, publisher : forouzan


0 Comments