为什么需要Javascript bind()?
值
this是决定 如何 一个功能 叫 。如果是 您
调用该函数,则通常无需使用
.bind,因为您可以控制调用函数的方式,因此也可以控制其
this值。
但是,通常 不是 您调用函数。函数作为回调和事件处理程序传递给其他函数。他们被称为 其它 的代码,你有无法控制 如何
调用该函数,因此无法控制
this将引用。
如果您的函数需要
this设置为特定值,而您又不是调用该函数的人,则需要
.bind将该函数设置为特定
this值。
换句话说:
.bind允许您设置的值,
this而不是调用它 现在 。
这是引用/调用函数的比较:
+-------------------+-------------------+ | | | | time of | time of | |function execution | this binding | | | |+-------------------+-------------------+-------------------+| | | || function object | future | future || f | | || | | |+-------------------+-------------------+-------------------+| | | || function call | now | now || f() | | || | | |+-------------------+-------------------+-------------------+| | | || f.call() | now | now || f.apply() | | || | | |+-------------------+-------------------+-------------------+| | | || f.bind() | future | now || | | |+-------------------+-------------------+-------------------+
我还想知道为什么示例3解决了这个问题,以及示例2和示例3之间的区别。
示例1/2和3没什么不同。
storeMyName和
storeMyName2包含 的功能
,这是所谓的未来,而
storeMyName3包含调用的结果
myName.getName()的那一刻 。



