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

半城伤御伤魂 提交于 2019-12-13 00:34:52

问题


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

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



回答2:


You can write it like this:

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

instead of this.



来源:https://stackoverflow.com/questions/46601046/adding-a-method-to-an-object-that-is-inside-of-a-function-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!