【发布时间】:2016-03-29 16:11:21
【问题描述】:
我正在开发一个小型复古风格的横向卷轴太空射击游戏(或者,无论如何,这就是理论),我最近开始使用 IIFE 来管理我的单独“类”。
但是,我看到的大多数示例在声明变量时都倾向于使用var,例如var x = 0。不过我想知道,是否可以使用this.x = 0,如果可以,有什么好处或缺点吗?
我试过用谷歌搜索它,但找不到太多关于这个主题的信息,这让我认为这不是问题。
我的课如下;
var Player = function () {
// ------------------------------------------------------------------------------------------------
// PLAYER VARIABLES
// ------------------------------------------------------------------------------------------------
var w = 50;
var h = 50;
var x = 0;
var y = 0;
var color = 'white';
var projectiles = [];
// ------------------------------------------------------------------------------------------------
// BIND EVENTS TO THE GLOBAL CANVAS
// ------------------------------------------------------------------------------------------------
Canvas.bindEvent('mousemove', function(e){
y = (e.pageY - Canvas.element.getBoundingClientRect().top) - (h / 2);
});
Canvas.bindEvent('click', function(e){
createProjectile(50, (y + (h / 2)) - 10);
});
// ------------------------------------------------------------------------------------------------
// FUNCTIONS
// ------------------------------------------------------------------------------------------------
var createProjectile = function(x, y){
projectiles.push({
x: x,
y: y
})
};
var update = function(){
for(var p = projectiles.length - 1; p >= 0; p--){
projectiles[p].x += 10;
if(projectiles[p].x > Canvas.element.width)projectiles.splice(p, 1);
}
};
var render = function () {
Canvas.context.fillStyle = color;
Canvas.context.fillRect(x, y, w, h);
console.log(projectiles.length);
for(var p = 0; p < projectiles.length; p++){
Canvas.context.fillStyle = 'red';
Canvas.context.fillRect(projectiles[p].x, projectiles[p].y, 20, 20);
}
};
// ------------------------------------------------------------------------------------------------
// Exposed Variables and Functions
// ------------------------------------------------------------------------------------------------
return{
update: update,
render: render
}
}();
【问题讨论】:
-
this将指向词法范围,主要是非严格模式下的窗口。在严格模式下,this将是undefined。 -
@RajaprabhuAravindasamy:
this不指向词法范围。你不能在 JS 中引用作用域(例外:全局作用域和由with语句创建的作用域,因为它们是由对象支持的)。 -
@FelixKling 哦,谢谢。
//'this' value here function test(){ //how can i tell the this value outside of this function? }我曾经说过那是词法范围。我用完了技术术语。 :( -
您的 IIFE 看起来没有正确声明。应该是
var Player = (function() {})();IIFE 只是一个普通的函数调用。确定this值的六种方式见How the Value of This is Set。 -
@jfriend00 谢谢=)
标签: javascript this var