我需要帮助解决此问题;
let person = {
firstname: "Benjamin",
dog: {
named: "Louie",
owner: function() {
return this.named + " is " + this.firstname + "'s dog'";
}
}
}
console.log(person.dog.owner.call(person)); // prints undefined is Benjamin's dog' instead of Louie is Benjamin's dog'
我知道call()方法将引用没有属性-named的person对象。
是否可以使用bind()call()或apply()方法打印"Louie is Benjamin's dog'"
答案 0 :(得分:1)
您的named
键在dog
下。所以叫this.dog.named
let person = {
firstname: "Benjamin",
dog: {
named: "Louie",
owner: function() {
return this.dog.named + " is " + this.firstname + "'s dog'";
}
}
}
console.log(person.dog.owner.call(person));
答案 1 :(得分:1)
this.named
应该为this.dog.named
,因为named
属性位于dog
对象内部。
在这里检查:
let person = {
firstname: "Benjamin",
dog: {
named: "Louie",
owner: function() {
return this.dog.named + " is " + this.firstname + "'s dog'";
}
}
}
console.log(person.dog.owner.call(person));
答案 2 :(得分:1)
该函数需要一个对象,该对象具有firstname
和named
属性。
实现所需功能(不更改该功能)的唯一方法是创建一个包含它们的新对象,并将其传递给您提到的功能之一。
console.log(person.dog.owner.call({ firstname: "Benjamin", named: "Louie" }));