我正在开发一款小型复古风格的横向卷轴太空射击游戏(或者,无论如何,这就是理论),并且我最近开始使用 IIFE 来管理我单独的“类”。
但是,我见过的大多数示例在声明变量时都倾向于使用 var
,例如 var x = 0
。但我想知道是否可以使用 this.x = 0
,如果可以,有什么好处或缺点吗?
我尝试用谷歌搜索它,但找不到太多关于这个主题的信息,这让我认为这不是问题。
我的类(class)如下;
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
}
}();
最佳答案
are there any benefits or drawbacks?
缺点是在严格模式下,您将收到运行时错误(因为this
是未定义
)。
在非严格模式下,this
将引用 window
,因此 this.x = ...
创建一个全局变量(我猜这是你首先想要避免使用 IIFE 的情况)。
没有任何好处。
关于javascript - 在 IIFE 构造函数中使用 'This',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289599/