您好,这是我正在处理的一项挑战。有什么方法可以在不使用关键字 this 的情况下将 introduce 方法添加到 personStore
对象。非常感谢任何见解。
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 thepersonStore
object.Challenge 3/3
Without editing the code you've already written, add an
introduce
method to thepersonStore
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.
我的解决方案:
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
最佳答案
可以,但是使用 this
会简单得多。
此代码将 name
属性作为参数传递,但由于 introduce
函数已经可以通过 this
访问该属性作为内部属性>,有点浪费。
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);
关于javascript - 向js中函数内部的对象添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601046/