Your approach is wrong from the very beginning. Never do such things. I'll explain why. It may not fix the problem you are reporting; I don't even want to look at it, because it would be a waste of time, first of all. You need to fix more important thing.
Look at your definition of
bob
. (Do you always so impolitely name people not using capitalization? It's just by the way…)
The definition is perfectly fine, syntax and everything. You could use it perfectly, if there was only one
bob
, or
Bob
. But, after that, you have
mary
. Poor Mary spoils everything. At this point, your code is already dead, even if it worked. Imagine what could happened if you misspelled at least one property name. It would be too hard to locate the bug. Here is what you want to do instead:
var Person = function(firstName, lastName, phoneNumber, email) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.email = email;
}
var contacts = [
new Person("Mary", "Johnson", "(650) 888-8888", "mary.johnson@example.com"),
new Person("Bob", "Jones", "(650) 777-7777", "bob.jones@example.com")
];
Can you see the idea? You re-use creation of person and avoid the problem I mentioned. There is no need in the pointless function
add
.
Moreover, you can check up if two objects came from the same constructor:
var sameTypes = contacts[0].constructor === contacts[1].constructor;
var differentTypes = contacts[0].constructor === bob.constructor;
Don't understand my use of the word "types" literary: they are nor the types in the sense of JavaScript nor in the sense of OOP (nothing in JavaScript is really OOP; the concepts are fundamentally different).
Please understand that my suggestion is not forcing you to use different style; it's much more fundamental: I suggest you to avoid so brutal violation of more fundamental principle: Don't Repeat Yourself:
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[
^].
Please start from this point and see if you can cope with that simple problem and everything else.
—SA