javascript - prototype中this的疑问
PHP中文网
PHP中文网 2017-04-10 14:35:22
0
2
380

看代码

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?

PHP中文网
PHP中文网

认证0级讲师

모든 응답(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

Peter_Zhu

我觉得

A.prototype.init = function () {
    this.test = test.bind(this) // 看这里
    this.prototype.test = test(this) // 这里会报错,this.prototype是undefined ,
    //因为函数才有prototype ,还有__proto__,对象只有__proto__属性
    //虽然函数也是一种对象,但这里应该把函数与对象分开
}

init()里的this是根据谁来调用它来决定的
a.init()时this指向a
A.prototype.init()时this指向A.prototype

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿