0

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);
asked Oct 3, 2014 at 11:07
2
  • Please show your whole code including the line var character = {... Commented Oct 3, 2014 at 11:18
  • .length is not a method that you can call, but a number! Commented Oct 3, 2014 at 11:18

1 Answer 1

3

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.

answered Oct 3, 2014 at 11:09
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.