Deconstructing the assignment problem of "javascript" ES6

how to pass the method of object to function normally?
as follows:

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 is NaN

of course, you can pass an object directly to function without deconstructing it. You can call the method fullName ().

what should I do correctly?

Apr.19,2022

first of all, the firstName in your getFullName is misspelled.
secondly, there is no problem with this deconstruction, and the root of the problem lies in this .
solution:

    return this.firstName + this.lastName;

replace with

    return JK.firstName + JK.lastName;

in fact, this is a problem with this pointers. If you write like this, when you execute fullName (), this points to window.
while this.firstName and this.lastName are both undefined, of course NaN is returned when added.

can be changed to this:

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

the problem that this points to, you can go like 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);

Menu