1

Hi this is from a challenge I was working on. Is there any way i can add the introduce method to the personStore object without using the keyword this. Any insight is greatly appreciated.

Using Object.create

Challenge 1/3

Inside personStore object, create a property greet where the value is a function that logs "hello".

Challenge 2/3

Create a function personFromPersonStore that takes as input a name and an age. > When called, the function will create person objects using the Object.create method on the personStore object.

Challenge 3/3

Without editing the code you've already written, add an introduce method to the personStore object that logs "Hi, my name is [name]".

Side Curiosity

As a side note, was curious if there was a way to add the introduce method to the person object that sits inside of the personFromPersonStore function.

my solution:

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function () {
  console.log('Hi, my name is ' + this.name)
}

//Challenge 3 Tester
sandra.introduce(); // -> Logs 'Hi, my name is Sandra

2 Answers 2

1

You can, but using this is a lot simpler.

This code passes the name property as an argument, but as the property is already accessible to the introduce function as an internal property via this, it is a bit wasteful.

var personStore = {
    // add code here
  greet: function (){
    console.log('Hello');
  }
};

function personFromPersonStore(name, age) {
  var person = Object.create(personStore);
  person.name = name;
  person.age = age;
  person.greet = personStore.greet;
  return person;    
};

personStore.introduce = function (nm) {
  console.log('Hi, my name is ' + nm)
}

person1=personFromPersonStore('Fred',21);
person1.introduce(person1.name);

Sign up to request clarification or add additional context in comments.

Comments

0

You can write it like this:

personFromPersonStore("whatevername","whateverage").name 

instead of this.

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.