Reputation: 3797
I have a question regarding this snippet of code.
var names = ["John", "Jen", "Tony"];
var obj = {
prob: function () {
for (var i = 0; i < names.length; i++) {
document.write(names[i]);
console.log(names[i]);
}
},
trim: names.forEach(function(name) {
document.write(name)
console.log(name)
})
}
console.log("*********")
console.log(obj.prob());
console.log("*********")
If I run this code in my console I will get this:
John
Jen
Tony
*********
John
Jen
Tony
undefined
*********
That means that before my prob function that I call my trim function runs. Why is that? I didn't call it? Can I save it as a method on object and call it later when I need it?
Upvotes: 5
Views: 1084
Reputation: 7593
obj.prob
is being assigned a function declaration and is not invoked.
obj.trim
sets an call to the function forEach
.
This means when you are assign to the property you are also causing the code to run (this happens when you instantiate theobj
object, which explains the initial logging of names)
Wrap the invocation of forEach
into an anonymous function declaration (just like you did with the for loop for the prob
property):
var names = ["John", "Jen", "Tony"];
var obj = {
prob: function () {
for (var i = 0; i < names.length; i++) {
document.write(names[i]);
console.log(names[i]);
}
},
// the code in this function block will only run
// when trim is invoked
trim: function(){
names.forEach(function(){
document.write(name);
console.log(name)
});
}
};
Upvotes: 1
Reputation: 374
The names.forEach
is called trying to assign the return value to trim
. Putting it inside a function should work.
var names = ["John", "Jen", "Tony"];
var obj = {
prob: function () {
for (var i = 0; i < names.length; i++) {
document.write(names[i]);
console.log(names[i]);
}
},
trim: function () {names.forEach(function(name) {
document.write(name)
console.log(name)
})}
}
console.log("*********")
console.log(obj.prob());
console.log("*********")
console.log(obj.trim());
Upvotes: 8
Reputation: 5788
You just have to wrap your each
function inside function
var names = ["John", "Jen", "Tony"];
var obj = {
prob: function () {
for (var i = 0; i < names.length; i++) {
document.write(names[i]);
console.log(names[i]);
}
},
trim: function(){ names.forEach(function(name) {
alert();
document.write(name)
console.log(name)
})}
}
console.log("*********")
console.log(obj.prob());
console.log("*********")
Upvotes: 0