[英]Function methods .apply() .call() .bind()
I need help solving this; 我需要帮助解决这个问题;
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'
I know the call() method will refer to the person object which does not have the property - named. 我知道call()方法将引用没有属性-named的person对象。
Is there a way to use the bind() call() or apply() methods to print "Louie is Benjamin's dog'"
有没有一种方法可以使用bind()call()或apply()方法来打印"Louie is Benjamin's dog'"
Your named
key is under dog
. 您的named
密钥在dog
下。 So call it this.dog.named
所以称它为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));
this.named
should be this.dog.named
because named
property is inside dog
object. this.named
应该是this.dog.named
因为named
属性在dog
对象内部。
Check here: 在这里检查:
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));
The function requires an object that has a firstname
and a named
property. 该函数需要一个具有firstname
和named
属性的对象。
The only way to achieve what you want (without changing that function) would be to create a new object which has them and pass that to one of the functions you mentioned. 实现所需功能(不更改该功能)的唯一方法是创建一个包含它们的新对象,并将其传递给您提到的功能之一。
console.log(person.dog.owner.call({ firstname: "Benjamin", named: "Louie" }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.