-2

I have this JavaScript block:

function List() {
 List.makeNode = function() {
  return {data: null, next: null};
 };

 this.start = null;
 this.end = null;

 this.add = function(data) {
  //some code
  this.end.data = data;
 };
}

My question is about the meaning of word this in those rows:

 this.start = null;
 this.add = function(data)

Thank you in advance.

Michael
  • 11,410
  • 43
  • 120
  • 228

2 Answers2

1

this points to the instance of the object. So if you were to do this:

var potato = new List();

potato would have (pretty much) properties assigned to it, called start and end. You would access them like this:

potato.start /* equals null, because the 
             function constructor set it to null 
             using the this keyword,
             this.start = null;
             */

You can try it yourself. Start your console (Ctrl+shift+j) and type in this:

function Foo(){
  this.length = 'bar';
  this.stuff = 'buzz';
}

Now try assigning it to a variable:

var foo = new Foo;

and accessing those properties.

foo.length
// returns 'bar'

foo.stuff
//returns 'buzz'

If you changed these:

foo.length = 'I have no length';

It would only apply to that instance, so if you were to do:

var foo2 = new Foo();

foo2.length
//still returns 'bar'

foo.length
// still 'I have no length'
theonlygusti
  • 7,942
  • 8
  • 40
  • 80
0
this.start = null;

initializes the property start on an instance of the List() class when you use it as a constructor. It will allow you to append additional properties or methods to List.start if you want to, as was done for List.end with List.end.data.

so

this.start = null;

allows you to say,

this.start.newProperty = "new"; 

If you didn't initialize this.start, most browsers would throw an error and most likely halt your program when you tried to create the new property.

this.add = function(data) {}

Creates a method for the List class, so that when you create an instance of List, you can all it like List.add()

Usage:

var myList = new List(); // Create a new instance of the List() class.

myList.add("my data"); // Store "my data" in myList.end.data via the add() method

alert(myList.end.data); // Would show "my data" in an alert box.

Hope this clarifies things a little bit.

James Marks
  • 183
  • 1
  • 6