Eddie Y
Eddie Y

Reputation: 15

Adding a method to an object that is inside of a function in js

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

Upvotes: 1

Views: 1296

Answers (2)

vertika
vertika

Reputation: 1424

You can write it like this:

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

instead of this.

Upvotes: 0

JMP
JMP

Reputation: 4467

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);

Upvotes: 1

Related Questions