「javascript」ES6 解构赋值問題

新手上路,请多包涵

请问如何把object的method正常传递给function?
如下:

let JK = {
  firstName: "John",
  lastName: "Kennedy",
  fullName: function() {
    return this.firstName + this.lastName;
  }
}

function getFullName({ fistName, lastName, fullName }) {
  console.log(fullName());
}

getFullName(JK);

console result 是 NaN

当然,可以不用解构直接pass个object给function可以调用到fullName()这个method。

正确该怎么做呢?

阅读 2.7k
6 个回答

首先,你的getFullName里面的firstName拼错了。
其次,这个解构没有问题,问题的根源在于this
解决办法:

    return this.firstName + this.lastName;

替换成

    return JK.firstName + JK.lastName;

其实这个是this指针的问题,像你这样写呢,执行fullName()时, this指向window。
而this.firstName 和 this.lastName 都是undefined, 相加的时候当然返回NaN.

可以改成这样:

function getFullName(person) {
  const { firstName, lastName, fullName } = person;
  console.log(person.fullName());
}

this指向的问题,可以这样:

let JK = {
    firstName: "John",
    lastName: "Kennedy",
    fullName: function(firstName, lastName) {
        return firstName + lastName;
    }
}

function getFullName({ firstName, lastName, fullName }) {
    console.log(fullName(firstName, lastName));
}

getFullName(JK);

getFullName方法改一下就可以了

let JK = {
  firstName: "John",
  lastName: "Kennedy",
  fullName: function() {
    return this.firstName + this.lastName;
  }
}

function getFullName(obj) {
  console.log(obj.fullName());
}

getFullName(JK);

其实正是因为JK对象被解构了。
所以fullNameJK中的方法变成了一个单独的函数,进而导致函数内部的this指向了全局对象。

let JK = {

firstName: "John",
lastName: "Kennedy",
fullName: function(firstName, lastName) {
    return firstName + lastName;
}

}

function getFullName({ firstName, lastName, fullName }) {

console.log(fullName(firstName, lastName));

}

getFullName(JK);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题