vue 源码中 这个this 指向谁?

如下 this.componentInstance 这个this 指向谁? 为什么?

var prototypeAccessors = { child: { configurable: true } };

// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
  return this.componentInstance   //这个this 是指向谁? 为什么?
};

Object.defineProperties( VNode.prototype, prototypeAccessors );
阅读 2.7k
4 个回答

js 函数中的 this 指向是由调用方式决定的。

这段代码等价于:

Object.defineProperties( VNode.prototype, {
    child: {
        configurable: true,
        get: function(){ return this.componentInstance; }
    }
} );

那个函数最终其实是 VNode.prototype.child 的 getter,那么推测被调用的方式肯定是通过 Vnode 实例访问 child 属性:

// 内部执行了 getter,getter 内部 this 指向 vnode
var child = vnode.child;
child === vnode.componentInstance;

这里指向的是VNode

this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁

在这里指向的是VNode。

可以看看这篇文章细说JavaScript中this指向问题

楼上各位大佬已经说的很明白了,谁调用就指向谁
**Object.defineProperty()** 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
Object.defineProperty(obj, prop)
所以就是`
VNode

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题