As an exercise, I am trying to create my own bind() function using apply() and prototypal inheritance that I have just learned.
This is my code:
// Create your own bind() using call() and apply()
const lizard = {
phrase: 'slither',
say(phraseToSay) {
if (!phraseToSay) phraseToSay = this.phrase
console.log('sss' + phraseToSay)
},
}
const dragon = {
phrase: 'sizzle',
}
// My Answer
Function.prototype.mybind = function (object) {
return () => this.apply(object, arguments)
}
// Solution
Function.prototype.solbind = function (object) {
let self = this
return function () {
self.apply(object, arguments)
}
}
dragon.say = lizard.say.mybind(dragon)
lizard.say()
dragon.say()
lizard.say('sexy')
dragon.say('sexy')
This is the Output:
ssslither
sss[object Object]
ssssexy
sss[object Object]
The solution is to use self=this. But it looks ugly in my eyes...
I am trying to do it with just this and arrow functions. But for some reason, apply() is passing the first argument which is the object itself as an actual argument of the target function. I do not understand why this is and how I can achieve the result I want without saving this into another variable.