I am studying JavaScript and I am trying to produce an object with a property that is a function. However, when logging character.strength in the console I just get the function without being executed. What would be the correct syntax?
name: "Jack",
age: 19,
strength: function() {
character.name.length() + name.age;
}
};
console.log(character.strength);
1 Answer 1
You need to call the function:
console.log(character.strength());
You can also implement a getter property:
{ get strength() { return this.name.length.toString() + this.age; } }
...and access the value as you did in your code sample:
console.log(character.strength);
Anyway, note that you've an issue in your code. It's not character.name.length(). length is a String object property, thus you need to access it without parenthesis (character.name.length)!
And, also, you're not accessing name and age properties of your object... you need to reference object properties with this keyword within the functions or properties of some given object.
Comments
Explore related questions
See similar questions with these tags.
var character = {....lengthis not a method that you can call, but a number!