在 IIFE 构造函数中使用 'This'

Using 'This' within an IIFE constructor

我正在开发一款小型复古风格的横向卷轴 space 射击游戏(或者,这就是理论),我最近开始使用 IIFE 来管理我的独立 'classes'.

然而,我看到的大多数示例在声明变量时倾向于使用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
    }
}();

are there any benefits or drawbacks?

缺点是在严格模式下,你会得到一个运行时错误(因为thisundefined)。
非严格模式 中, this 将引用 window,因此 this.x = ... 创建一个全局变量(这是你想要避免的我猜是 IIFE)。

没有好处。