我需要你的帮助。我被这些代码行卡住了
var bind = Function.call.bind(Function.bind);
bind(CC, Components);我试着理解它们是什么以及它们是如何工作的,但我不能:
谢谢你的帮助。
发布于 2015-10-19 15:35:42
1. Function#bind和独立的bind函数是什么?
Function#bind
对Function#bind的调用将创建一个新函数,该函数将永久绑定到作为第一个参数传递的上下文。Function#bind作为函数的一个方法进行操作。也就是说,您只能绑定调用Function#bind的函数。
let str = 'Hello, World!'
let fn = () => console.log(this)
// Bind the `this` to be `str`
let boundFn = fn.bind(str)
boundFn() // => 'Hello, World!'
// Attempt re-bind:
boundFn = fn.bind('new str')
boundFn() // => 'Hello, World!'______
Function#call
Function#call不同于Function#bind,因为它使用给定的上下文和任何其他参数执行给定函数的。它不返回新的绑定函数。
let str = 'Hello, '
let fn = (who) => console.log(this + who)
fn.call(str, 'World!') // => 'Hello, World!'______
通过引用传递函数将失去其上下文。
当我们通过引用传递一个函数时,就失去了它的上下文。在这种情况下,这意味着我们不能简单地执行var bind = Function.bind并调用bind作为独立函数。
let log = () => console.log('Hello, World!')
let bind = Function.bind;
bind(log) // => Uncaught TypeError: Bind must be called on a function______
创建独立函数bind
您共享的代码创建了一个与Function#bind等价的速记(独立)函数,但它接受要绑定的函数作为其第一个参数,并接受将该函数绑定到的上下文作为其第二个参数,而不是作为绑定函数的成员调用bind方法(例如,fn.bind(ctx))。
// Create standalone `bind` function
let bind = Function.call.bind(Function.bind);
let obj = { hello: 'World!' }
let log = () => console.log(this)
let boundFn = bind(log, obj)
boundFn() // => { hello: 'World!' }______
2.如何在不使用Function#bind的情况下实现此功能
上面的解决方案接受定义返回函数的上下文(this)的函数和第二个参数。我们可以非常简单地通过一个助手函数来模仿这个功能,该函数接受相同类型的参数,并返回一个函数,在调用该函数时,该函数使用Function#call使用给定的上下文和参数执行该函数。
例如:
function bind (fn, ctx) {
return function (...args) {
fn.call(ctx, ...args);
};
}请注意,这与创建绑定函数并不完全相同。你可以 in the spec。
发布于 2015-10-19 15:16:57
bind正确工作,您必须生成一个函数,其中this是Function.bind。注意call的签名:
.call(thisArg[,arg1[,arg2,.])
因此,此执行返回绑定到Function.bind的函数。在您的具体情况下,它将CC绑定到Components,因此当您调用CC()时,上下文(this)将是Components。let bind = (fn, ...args) => fn.bind(...args);https://stackoverflow.com/questions/33217983
复制相似问题