在Javascript中使用apply()创建我自己的bind()函数



作为一个练习,我试图使用刚刚学到的apply((和原型继承创建自己的bind((函数。

这是我的代码:

// 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')

这是输出:

ssslither
sss[object Object]
ssssexy
sss[object Object]

解决方案是使用self=this。但在我眼里它看起来很难看。。。我正试图用这个和箭头函数来实现它。但由于某种原因,apply()正在传递第一个参数,即对象本身作为目标函数的实际参数。我不明白为什么会这样,也不明白如何在不将this保存到另一个变量中的情况下实现我想要的结果。

当你这样做时:

.... = function (object) { 
return () => this.apply(object, arguments)
}

您指的是绑定到外部函数表达式的arguments对象,而不是您的箭头函数,因为箭头函数没有自己的参数绑定。在这种情况下,arguments对象将包含dragon,正如您使用的:

dragon.say = lizard.say.mybind(dragon)

因此,arguments对象将包含dragon,当使用.apply(object, arguments)时,它将作为参数传递给say方法。

在所提供的解决方案中,它们返回一个函数表达式,与箭头函数不同,该函数表达式有自己的arguments绑定,因此在这种情况下,arguments对象引用传递到solbind()返回的函数中的参数。

您可以使用ES6 rest参数语法(...)而不是引用arguments对象来修复代码。以这种方式CCD_ 13将引用传递到";绑定";功能:

// 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 (...args) => this.apply(object, args)
}
// 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')

相关内容

最新更新