Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unable to understand the "this" keyword

Status
Not open for further replies.

renzocj

Programmer
Sep 1, 2011
8
PE
As much as I try, I have read and tried many exercises and examples to understand the keyword "this" but so far I cannot understand how it works. The fact that "represents" objects confuses me too much. On my way to continue learning this language, I have hope that someone here can explain me, in his best attempt, to understand how it works.

I've also been trying to understand how this example works because it might help me to learn the subject:

Code:
//function to be invoked as a method from a "car" object

function showCar() {
alert(this.make + " : " + this.color)
}

//"car" object constructor function

function Car(make,color) {
this.make=make;
this.color=color;
this.show=showCar;

//create instance of a "car" object

var myCar=new Car("Ford","blue");

myCar.show();
}

Example from:

JavaScript Bible
Seventh Edition
Part III - JavaScript Core Language Reference
Chapter 23 - "Function Objects and Custom Objects"
Page: 446

I appreciate in advanced any help in teaching me this "this".
 
In its simplest form its an internal reference.

Basically what it does it give you a way to access the object under which the current code is being run.

In the case of your example, it references the Car object being created, so you can set its properties make and model.





----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
it looks like you are missing some syntax but the general premise is there.
everything is JS is an object. "this" is the keyword used to access the current object's members.

I don't know if this would confuse you more, or help clarify, but you could write the same functionality this way
Code:
var car = {
   make: 'Ford',
   color: 'Blue',
   show: function(){
      alert(this.make + ' : ' + this.color);
   }
};
car.show();

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top