+ 2
What is the function of "this" keyword in javascript
8 Respostas
+ 4
Hi zredhard
As the "this" keyword is probably the most misunderstood thing in JavaScript, I find it easier to have a basic understanding of Why you even need it, before the What and the How.
First remember that in JavaScript Functions are Objects.
Lets say you want to create an Object that represents your monsters in a game, and you are going to have 20 monsters in your game.
You could code up 20 Objects each one representing 1 of your monsters. That is alot of coding, and is prone to mistakes and would not allow you to add additional monsters or remove them as your game required.
So the shorthand way is to create a constructor function (think of it as a template for your monsters), and instantiate versions of our monster using the "new" keyword ie:
//constructor function
function monster (name,life){
this.name=name;
this.life=life;
}
//create new monsters
var monster1 = new monster("Greenslime",10);
var monster2= new monster("Pricklyball",15);
console.log (monster1.name);
//Greenslime
console.log (monster2.name);
//Pricklyball
Now you can see that the constructor function uses the "this" keyword to refer to whatever created(called) it , ie monster1 and monster2.
Without "this" how would we know what the name of the new monster would be?
So we use "this" to assign the values of "name", and "life" to our new instance of our monster1 and monster2, like a proxy or alias of their names.
There are more complex uses for "this", but if you can grok the above you will have a good start.
+ 2
can i know what is constructor function?
+ 2
sure, constructor function is a function that creates objects.
In other words-
It holds the skeleton of an object.😂😂
+ 1
As far as i know and understand it points to the object its creating.
Its used for creating constructor functions.
+ 1
1
+ 1
'this' refers/points to a variable that belongs to an object. it's used on object constructors.
taken you have a object 'car', this.speed, this.color etc. are variables which belong to the object 'car'.
+ 1
'This' has binding to this function-constructor. When you create objects using word 'new', there is a new scope for this object
+ 1
ok thank you all