Reputation: 516
I want to use the init() method to initiate objects taken from an associative array by a for..in loop:
var person = {name: null, id: null}
person.init = function(name){
this.name = name;
this.id = "##" + this.name;
}
var pers1 = Object.create(person);
var pers2 = Object.create(person);
var personArray = {pers1: "John", pers2: "Alice"};
for (var i in personArray){
console.log(i);
console.log(personArray[i]);
console.log(i.name);
i.init(personArray[i]);
}
Output:
pers1
John
undefined // pers1.name
TypeError: i.init is not a function //But not pers1.init() ?
Why can I call the .name attribute but not the .init() method? And more importantly, is there a way to call the methods of objects in an array?
I am a beginner at JS so I'm sorry if the code looks a bit weird.
Upvotes: 0
Views: 52
Reputation: 1075159
Why can I call the .name attribute but not the .init() method?
In JavaScript, you can access non-existent properties on objects; when you do, you get back the value undefined.
That's what you're doing: The values of the properties on personArray
(which isn't an array) are strings, and don't have name
or init
properties. That's fine for accessing .name
, because all you do is pass it to console.log
, but you get an error for .init
because you're trying to call undefined
as a function.
The main issue is that your properties in the object (it's not an array) are not related in any way to your person
function, and are not related in any way to your pers1
and pers2
objects.
If your goal is to start with an object with properties whose values are just names, and convert it into an object with objects using those names backed by the person
object, you can do this:
var person = {name: null, id: null};
person.init = function(name){
this.name = name;
this.id = "##" + this.name;
};
var personMap = {pers1: "John", pers2: "Alice"};
var name;
for (var i in personMap) {
name = personMap[i];
personMap[i] = Object.create(person);
personMap[i].init(name);
}
Upvotes: 1
Reputation: 1309
var personArray = {pers1: "John", pers2: "Alice"};
this line is creating a new Object which only contains the keys pers1
and pers2
assigned to the strings "John"
and "Alice"
, you aren't assigning the objects you have created
Upvotes: 0