Home > Back-end >  How the first object can use the method of second object?
How the first object can use the method of second object?

Time:10-05

using the Object.setPrototypeOf(), player2 can use player1 method, but how can the player1 can use player2 method in this example?

let player1 = {
  kick() {
    return 'kicking..';
  }
};


let player2 = {
  smash() {
    return 'smashing..';
  }
};

Object.setPrototypeOf(player2, player1);

console.log(player2.kick());

CodePudding user response:

Instead of changing the prototype, you can copy one object's properties into the other using Object.assign():

const player1 = {
  kick() {
    return 'kicking..';
  }
};


const player2 = {
  smash() {
    return 'smashing..';
  }
};

Object.assign(player2, player1);
Object.assign(player1, player2);

console.log(player2.kick());
console.log(player1.smash());

  • Related