vue.js methods中的方法互相调用时变量的vue 作用域是怎样的

2025-03-03 18:46:20
推荐回答(1个)
回答1:

methods中的function中的this指向vue实例,其他的没什么这种调用方式是直接访问test2函数,没有任何的this绑定,所以肯定访问不到

this.$options.methods.test2();

而直接调用this.test2(),内部肯定做了this绑定的,例如

this.$options.methods.test2.bind(this)();

更新:Vue源码中的处理

/**
* Setup instance methods. Methods must be bound to the
* instance since they might be passed down as a prop to
* child components.
*/
Vue.prototype._initMethods = function () {
var methods = this.$options.methods
if (methods) {
for (var key in methods) {
this[key] = bind(methods[key], this)
}
}
}

function bind (fn, ctx) {