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);