Bind object with value - Node.js Object

Node.js examples for Object:Object Operation

Description

Bind object with value

Demo Code


Function.prototype.myBind = function (ctx, ...bindArgs) {
  return (...callArgs) =>  {
    return this.apply(ctx, bindArgs.concat(callArgs));
  };//  w  ww  . j  ava 2  s.co  m
};

class Cat {
  constructor(name) {
    this.name = name;
  }

  says(sound, person) {
    console.log(`${this.name} says ${sound} to ${person}!`);
    return true;
  }
}

const markov = new Cat("Markov");
const breakfast = new Cat("Breakfast");

// bind time args are "meow" and "Kush", no call time args
markov.says.myBind(breakfast, "meow", "Kush")();
// Breakfast says meow to Kush!
// true

// no bind time args (other than context), call time args are "meow" and "me"
markov.says.myBind(breakfast)("meow", "a tree");
// Breakfast says meow to a tree!
// true

// bind time arg is "meow", call time arg is "Markov"
markov.says.myBind(breakfast, "meow")("Markov");
// Breakfast says meow to Markov!
// true

Related Tutorials