0

Possible Duplicate:
JavaScript “this” keyword

I have written a function called add with the parameters firstName, lastName, and email, telephone. In this new function, the intention is to create a new contact object like bob and mary.

My question is concerning the context and use of the this keyword. this is allowing me to set the newly created object's property values to the appropriate add function parameters that are passed in. What is the purpose if this and what is this one word allowing me to do within the code? Is it to enable functionality that allows any string to be passed through the function parameters in order so that multiple objects can be created?

I used the this keyword recently to enable me to use the same function on multiple objects, without having to write a separate function on a per object basis. For example a function that could set the age property for all objects, rather than a separate age changing function per object.

Secondly, I wanted to check if my understanding of the way in which the data is inserted into the appropriate position in the contacts array is correct. Finally, May I also ask the context of the this keyword here?

contacts[contacts.length] = this; 

which is the same as:

contacts[2] = this;

My apologies if I haven't phrased my question in most succinct way. Please find my code below. Any answers or explanations of the this keyword for this coding situation would be massively appreciated.

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777 - 7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",  
    phoneNumber: "(650) 888 - 8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

    function add(firstName, lastName, email, telephone){
    this.firstName = firstName; 
    this.lastName = lastName;
    this.email = email;
    this.telephone = telephone;
    contacts[contacts.length] = this
    }

    var response1 = prompt("First Name?");
    var response2 = prompt("Last Name?");
    var response3 = prompt("Email?");
    var response4 = prompt("Telephone No.?");
    add(response1, response2, response3, response4);
Community
  • 1
  • 1
user1554264
  • 1,102
  • 3
  • 16
  • 45

3 Answers3

0

this in your add function actually refers to the global window object, so you are adding that to your array instead of a new contact.

You need to create a new object inside that function and add that to the array:

function add(firstName, lastName, email, telephone){
    var newContact = {
        firstName: firstName,
        lastName: lastName,
        email: email,
        telephone: telephone
    }
    contacts[contacts.length] = newContact;
}

Here is a good reference for this - http://bonsaiden.github.com/JavaScript-Garden/#function.this

If you really want to use this, you can specify what this refers to by calling the function using call or apply:

add.call({}, response1, response2, response3, response4); // pass new object as this
add.apply({}, [response1, response2, response3, response4]); // pass new object as this
Richard Dalton
  • 34,315
  • 6
  • 69
  • 88
0

this is all about scope and context. It refers to the wider context in which it is used.

Here's an example:

function MyObject(one,two) {
this.one = one;
this.two = two;
}

Myobject.prototype.SayNumbers() {
alert(this.one + this.two);
}

var myobj = new MyObject("Foo","Bar");
myobj.Saynumbers();

In the context of the example above, this 'belongs' to the function it was used within - the 'myobj' object. That allows it to access the object's properties and alert them.

If you used the this keyword in global scope (i.e. not inside a function/object), it would refer to the window object.

this can also be passed around by reference - which is useful for event handlers. For an onclick event, you can pass this along through to the event handling function and do things with the clicked object.

Try experimenting and doing a bit of research - this site has some good examples: http://www.quirksmode.org/js/this.html

James
  • 10,716
  • 1
  • 15
  • 19
0

The this keyword sometimes serves a practical purpose:

  • For SOMETHING.add(response1, response2, response3, response4), this would be SOMETHING.

  • For SOMETHING = new add(response1, response2, response3, response4), this would be the newly created object SOMETHING.

However, when you call add() as a function rather than as a method, this is the global (window) object. Therefore, you are just creating four global variables (firstName, lastName, email, and telephone), which you are overwriting each subsequent time you add an entry to the array. Note that if your code were executed in the opt-in "ES5 strict mode" of a recent JavaScript interpreter, the first line of your add() function would cause a runtime error.

(If you want more to read, see How does the "this" keyword work?.)

In your case, I would avoid this and instead explicitly create a new object.

function add(firstName, lastName, email, telephone){
    var obj = {
        firstName: firstName,
        lastName: lastName,
        email: email,
        telephone: telephone
    };
    contacts[contacts.length] = obj;
}

Regarding contacts[contacts.length] = obj;, an alternative is to use contacts.push(obj);. However, the way you have it is perfectly fine, and in fact, might perform slightly better. Just choose whichever you prefer.

Community
  • 1
  • 1
PleaseStand
  • 29,519
  • 6
  • 64
  • 94