函数方法.apply().call().bind()

时间:2018-07-13 12:27:51

标签: javascript

我需要帮助解决此问题;

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'"

3 个答案:

答案 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)

该函数需要一个对象,该对象具有firstnamenamed属性。

实现所需功能(不更改该功能)的唯一方法是创建一个包含它们的新对象,并将其传递给您提到的功能之一。

console.log(person.dog.owner.call({ firstname: "Benjamin", named: "Louie" }));