87,910
社区成员
发帖
与我相关
我的任务
分享
需要传参数的话就需要再包裹一层函数
setInterval(function () {
(function (a) {
//code
})(123)
}, 1000);
或者在ie9以后可以用 bind()
setInterval(function (a) {
//code
}.bind(this,123), 1000);
function Satellite(id, speed) {
this.id = id;
this.speed = speed;
this.power = 100;
this.state = "stop";
setInterval((function (_this) {
return function () {////////返回setInterval要执行的函数,你不家这句是将执行此函数的返回值作为setInterval要执行的代码,没有返回值当然只执行一次
if (_this.state == "run" && _this.power > 0) { _this.power -= 1; }
else if (_this.state == "stop" && _this.power < 100) { _this.power += 1; }
else { _this.state = "stop"; }
console.log(_this);
}
})(this), 1000);
}
var test = new Satellite(1,10);
test.state = "run";
function Satellite(id,speed) {
this.id = id;
this.speed = speed;
this.power = 100;
this.state = "stop";
var _this = this;
setInterval(function () {
if(_this.state == "run" && _this.power >0 ){_this.power -= 1;}
else if(_this.state == "stop" && _this.power<100 ){_this.power += 1;}
else {_this.state = "stop";}
console.log(_this);
},1000);
}