0

Considering This:

  var genericGreet = function() {
    return "Hello, my name is " + this.name;
  }

  var andrew = {
    name: "Andrew",
    greet: genericGreet
  }

  var ryan = {
    name: "Ryan",
    greet: genericGreet
  }

</script>

Why is it wrong to say greet: genericGreet() or greet: genericGreet();. The above is from an interactive quiz in a series of online learning for javascript at treehouse.com, and the interactive quiz is telling me that these would be incorrect, and I don't know why.

1 Answer 1

1
greet: genericGreet

will let greet also to point to the object pointed by genericGreet. So, greet is now an alias for the same function. But when you say

greet: genericGreet()

you are making greet point to the returned value of the genericGreet function. If you intend to call greet later on, then you should use

greet: genericGreet

only. Normally, people use Prototypal pattern to implement this

function PersonGreeter(personName) {
    this.name = personName; 
}

PersonGreeter.prototype.greet = function() {
    return "Hello, my name is " + this.name;
};

var andrew = new PersonGreeter("Andrew");
console.log(andrew.greet());
var ryan   = new PersonGreeter("Ryan");
console.log(ryan.greet());

Output

Hello, my name is Andrew
Hello, my name is Ryan
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.