问题
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
personStoreobject, create a property greet where the value is a function that logs "hello".Challenge 2/3
Create a function
personFromPersonStorethat takes as input a name and an age. > When called, the function will create person objects using the Object.create method on thepersonStoreobject.Challenge 3/3
Without editing the code you've already written, add an
introducemethod to thepersonStoreobject 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