+ 2

What is the function of "this" keyword in javascript

20th Apr 2018, 4:09 AM
zredhard
zredhard - avatar
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.
20th Apr 2018, 2:46 PM
Mike Choy
Mike Choy - avatar
+ 2
can i know what is constructor function?
20th Apr 2018, 6:47 AM
zredhard
zredhard - avatar
+ 2
sure, constructor function is a function that creates objects. In other words- It holds the skeleton of an object.😂😂
20th Apr 2018, 10:33 AM
Akib
Akib - avatar
+ 1
As far as i know and understand it points to the object its creating. Its used for creating constructor functions.
20th Apr 2018, 4:33 AM
Akib
Akib - avatar
+ 1
1
20th Apr 2018, 9:07 AM
Владислав Романов
Владислав Романов - avatar
+ 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'.
20th Apr 2018, 10:43 AM
wenz
wenz - avatar
+ 1
'This' has binding to this function-constructor. When you create objects using word 'new', there is a new scope for this object
20th Apr 2018, 12:42 PM
Sergey Vishnevsky
Sergey Vishnevsky - avatar
+ 1
ok thank you all
20th Apr 2018, 3:46 PM
zredhard
zredhard - avatar