Reputation: 499
I'm trying to create a property within an object and I want the value to be whatever is returned from a method within the same function:
var model = {
generateRandomNumber: function(){
var randomNumber = Math.floor(Math.random() * 101);
return randomNumber;
},
generatedNumber: this.generateRandomNumber()
};
But I get an error: Uncaught TypeError: undefined is not a function
I just want to have the new property to contain whatever is returned from the method within the same object.
Upvotes: 1
Views: 70
Reputation: 301
Your problem is with your referencing, using this.generateRandomNumber inside an object.. that won't work. Why not just do this:
var model = {
generateRandomNumber: function() {return Math.floor(Math.random()*101;}, generatedNumber: Math.floor(Math.random()*101};
This would have the same effect.
Upvotes: 0
Reputation: 1071
The function generateRandomNumber is not accessible within the object declaration because the object literal hasn't been fully parsed. Try this:
var obj = {
generateRandomNumber: function() {
return this.generatedRandomNumber = Math.floor(Math.random() * 101);
}
}
obj.generateRandomNumber();
alert(obj.generatedNumber);
Upvotes: 0
Reputation: 943108
You can't access the object (to call the function) until after the object exists.
You have to do this in two steps:
var model = {
generateRandomNumber: function(){
var randomNumber = Math.floor(Math.random() * 101);
return randomNumber;
}
};
model.generatedNumber = model.generateRandomNumber()
Since the method doesn't depend on this
(which begs the question of why it is an object method in the first place), you could define the function separately instead.
function generateRandomNumber (){
var randomNumber = Math.floor(Math.random() * 101);
return randomNumber;
}
var model = {
generateRandomNumber: generateRandomNumber,
generatedNumber: generateRandomNumber()
};
Upvotes: 4