有关javascript中关键字THIS的问题[重复]

问题描述 投票:0回答:1

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

var MyFather = new Person('John', 'Doe', 22, "blue");

function getName() {
  let name = this.firstName + ' ' + this.lastName;
  return name;
}

MyFather.getName = getName;
//Will Return John Doe
console.log(MyFather.getName());

var getAge = () => {
  let age = this.age;
  return age;
}

MyFather.getAge = getAge;
//will return undefined
console.log(MyFather.getAge())

在上面的代码中,函数get-name将返回所需的结果。但是,当我使用arrorw函数获取getAge时,它将返回undefined。

我知道箭头功能中的关键字this表示窗口对象。反正还有年龄吗?使用此

javascript this
1个回答
-1
投票

尝试一下。

var getAge = () => {
  let age = this.age;
  return age;
}

MyFather.getAge = getAge.bind(MyFather);
//will return undefined
console.log(MyFather.getAge())
© www.soinside.com 2019 - 2024. All rights reserved.