脚本宝典收集整理的这篇文章主要介绍了Vue 源码阅读(七) bind,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。
class Demo { constructor() { this.num = 1 this.inIT() } resize() { alert(this.num) } init() { window.addEventListener('resize', this.resize) } } new Demo()
代码执行后,缩放浏览器,此时弹窗显示 undefined
。
符合预期!!
import Vue From 'vue' new Vue({ template: '<div></div>', data: { num: 1 }, methods: { resize() { alert(this.num) } }, mounted() { window.addEventListener('resize', this.resize) } }).$mount('#app')
缩放浏览器,此时弹框显示 1
。
不符合预期!!
按常理,绑定事件 this.resize
后,将会丢失 this
所指向的上下文,所以第一个代码执行的结果是 undefined
。
因此猜想,在 Vue 的实现版本中,绑定是一定不是定义在 methods
下的 resize
方法。
src/core/instance/state.js#L258
function initMethods (vm: component, methods: Object) { const PRops = vm.$options.props for (const key in methods) { // ... vm[key] = methods[key] == null ? noop : bind(methods[key], vm) } }
可以看到在 Vue 实例上绑定的方法,都是被 bind
处理过的。
function polyfillBind (fn: Function, ctx: Object): Function { function bounDFn (a) { const l = arguments.length return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length return boundFn } function nativeBind (fn: Function, ctx: Object): Function { return fn.bind(ctx) } export const bind = Function.prototyPE.bind ? nativeBind : polyfillBind
由此可见, Vue 的实例调用的方法,是经过 bind
后带有上下文的新方法。
觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! vue,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的Vue 源码阅读(七) bind全部内容,希望文章能够帮你解决Vue 源码阅读(七) bind所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。