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 appre
Solution 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 heregreet: function (){
console.log('Hello');
}
};
functionpersonFromPersonStore(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);
Solution 2:
You can write it like this:
personFromPersonStore("whatevername","whateverage").name
instead of this.
Post a Comment for "Adding A Method To An Object That Is Inside Of A Function In Js"