首页 > 解决方案 > 函数方法 .apply() .call() .bind()

问题描述

我需要帮助解决这个问题;

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() 方法将引用不具有属性的人员对象 - 命名。

有没有办法使用 bind() call() 或 apply() 方法来打印"Louie is Benjamin's dog'"

标签: javascript

解决方案


你的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));


推荐阅读