ToggleParticle改写以后出现的一个问题

我在ToggleParticle里面加了一个progressBar,想实现当进度条满的时候,点击触发粒子的发射,粒子发射后进度条清零重新填满。功能实现了,但是里面有个关于this作用域的问题很奇怪,希望哪位大神可以解答下。

下面是代码:
cc.Class({
extends: cc.Component,

properties: {
    particle: {
        default: null,
        type: cc.Node
    },
    
    progressBar:{
        default:null,
        type:cc.ProgressBar
    },
 
   speed:5,
},

onLoad: function () {
this.progressBar.progress = 0;
this.ready = false;
this.setInputControl();
},

setInputControl: function(progressBar) {
_ var self = this;_
_ this.node.on(‘mousedown’, function(){_
_ console.log(‘mousedown’);_
_ console.log(self);_
_ console.log(this);_
_ self.toggleParticlePlay();_
_ self.progressBar.progress=0;_
_ }.bind(this)); _
_ },_

toggleParticlePlay: function() {
var myParticle = this.particle.getComponent(cc.ParticleSystem);
if (myParticle.isFull()) { // check if particle has fully plaed
myParticle.stopSystem(); // stop particle system
} else {
myParticle.resetSystem(); // restart particle system
}
},

update: function (dt) {
    this._updateProgressFull(this.progressBar,dt);
    if (this.ready) {
        this.setInputControl(this.progressBar);
        this.ready = false;
    }
},

_updateProgressFull: function (progressBar,dt) {
  var progress = progressBar.progress;
  if(progress<1.0 && !this.ready) {
      progress +=dt*this.speed;
      progressBar.progress = progress;
     } else if (progress>=1) {
         progressBar.progress=1;
         this.ready=true;
     }
},

});

setInputControl: function(progressBar) {
   var self = this;
   this.node.on('mousedown', function(){
       console.log('mousedown');
       console.log(self); -->控制台里面打印出来是ParitcleControl这个节点
       console.log(this); -->***控制台里面打印出来居然是null,这是为什么啊?**
       self.toggleParticlePlay();
       self.progressBar.progress=0;
       }.bind(this.background));
    
},

有没有人知道啊?

你发了那么多凌乱的代码,有用的用setInputControl一个函数啊。学会用论坛的代码格式化功能,把代码用三个`(数字1前面那个键)包围起来,像这样:

你console.log(self)打印出来是前面定义的var self = this;没什么好说的,后面console.log(this);打印出来是null是因为函数后面有一个.bind(this.background),这个this.background是null吧?

谢谢大神,把this.background改成this后,确实指向了Particle control这个节点了。
我当时设置this.background目的是想点击整个屏幕而不是只是点击particle control这个节点起作用。
但是改成this.background以后,仍然是点击particle control这个节点才能运行,也就是说这个加了没有用。

不过还有一个不清楚的,this.background 里面的this应该还是particle control啊,因为我把background这个节点绑定到了particle control这个节点了,怎么又会是null呢?this 不是要么指向全局window要么指向某个对象,什么都不指,感觉this这个指针是蒙圈了,这是什么意思呢?

你想把事件添加到this.background上,就该添加this.background.on事件,而不是把ParticleControl节点上事件的回调函数bind到this.background上,没有用。
bind会把函数里的this变成bind的第一个参数,见:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
你在运行setInputControl的时候,估计你的this.background还没有初始化,还是null。所以回调函数里console.log(this)就是null。
this的作用域问题:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

谢谢大神,我仔细看一下。
我的很多问题都是您帮我解答的,你真是大神中的活雷锋啊。