prototype中this的疑问

看代码

function A () {
    this.init();
}

functin test () {
    console.log('test');
}

A.prototype.init = function () {
    this.test = test.bind(this) // 看这里
    this.prototype.test = test(this) // 还是这里
}

看上面代码中我标记的地方,我想动态绑定一个外部函数作为A对象的方法,init方法里的this是指function A呢还是A.prototype?

阅读 6.2k
2 个回答

动态绑定一个外部函数作为A对象的方法

function test() {
    console.log('test');
}

A.prototype.init = function() {
    this.test = test;
}

这样就可以了。

init方法里的this是指function A呢还是A.prototype?

var a = new A();
a.init();

以上面这样方式调用init方法的话,init方法中的this指向a

A.prototype.init();

以上面这样方式调用init的话,this指向A.prototype

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