Created
February 16, 2020 07:23
-
-
Save greathmaster/34715edf59fe3716ab1ab8a6040f0db7 to your computer and use it in GitHub Desktop.
JS binding, passing arguments at bind time and call time example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Dog(name, breed) { | |
this.name = name; | |
this.breed = breed; | |
} | |
Dog.prototype.sayHello = function(sound1, sound2) { | |
console.log(`The dog ${this.name}, a ${this.breed}, says Hello! And makes sounds ${sound1} and ${sound2}`) | |
} | |
function Cat(name, breed) { | |
this.name = name; | |
this.breed = breed; | |
} | |
let cat = new Cat("Salem", "calico") | |
//Let's "steal" the Dog's sayHello() method by using bind() | |
let catBurgler_1 = Dog.prototype.sayHello.bind(cat, "meow", "boo"); //Both arguments passed at bind time | |
let catBurgler_2 = Dog.prototype.sayHello.bind(cat, "meow"); //One argument passed at bind time, the other at call time | |
let catBurgler_3 = Dog.prototype.sayHello.bind(cat); //Both arguments passed at call time | |
catBurgler_1() //The dog Salem, a calico, says Hello! And makes sounds meow and boo | |
catBurgler_2("boo") //The dog Salem, a calico, says Hello! And makes sounds meow and boo | |
catBurgler_3("meow", "boo") //The dog Salem, a calico, says Hello! And makes sounds meow and boo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment