function A() {}
A.prototype.b = function(){
var dtd = $.Deferred();
var cha = function() {
dtd.resolve();
}
setTimeout(cha,5000);
return dtd;
}
A.prototype.wan = function() {
console.log("结束");
}
A.prototype.action = function(){
var that = this;
var b = function() {
return this.b.apply(this, arguments)
}.bind(this);
b().then(function(){
that.wan();
});
}
var a = new A(); a.action();
这是我copy的一段代码,其中
var that = this;
var b = function() {
return this.b.apply(this, arguments)
}.bind(this);
这一段的this指向真是考验脑细胞(全局? or A函数? or b方法?),原型方法b中的var that = this,这个this应该指向的A函数对象,this.b.apply(this...然后把this的b又指向this还不够 ,最后bind(this)又指向一次,彻底晕菜+_+?求高手指点迷津
如果我把最后一段
b().then(function(){
that.wan();
});
改成
b().then(function(){
this.wan();
}.bind(A));
维森么 会报错?显示一个this.wan is not a function
很不解?求高手相助...
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
this的作用域问题。个人有个小技巧是1.判断离最近的父
function,这里且叫fatherFunc2.
fatherFunc是构造函数或prototype函数,或者bind了对象,则this指向对象;否则this指向fatherFunc的调用环境:父函数正常调用
fatherFunc()时,this指向window或global;指定执行环境时
fatherFunc.apply(obj,args)或fatherFunc.call(obj,args),this指向对象obj;作为DOM事件处理函数:
element.addEventListener(eventType,fatherFunc);或element.onEventType = fatherFunc;,this指向DOM元素。以下示例:
三种颜色分别代表不同的this判断。
第一段,没有错的的代码里,所有的 this 都是
a,自己仔细理一理就好了,你该的错误代码里,
this是 promise 对象。http://zonxin.github.io/post/2015/11/javascript-this
同意一楼。
这个方法属于谁,this就指向谁
既然bind(this)了,那this就是this,也就是a
还有这命名作者你出来我保证打不死你
最后一个问题的话吧A改成a就行了, 很简单的理由: a是一个实例化对象, 而A是一个构造函数...
关于前面的this