JSLint严格模式违规。面向对象的JavaScript令人沮丧。

3

我想学习如何在JavaScript中进行面向对象编程,但是遇到了JSLint的严格违规提示。我知道这是因为我在非全局上下文中使用了this关键字(或类似的情况),但是我不知道该如何正确使用它。以下是我的代码:

function piece(color, type, x, y, captured, hasMoved) {
    "use strict";
    this.color = color;
    this.type = type;
    this.x = x;
    this.y = y;
    this.captured = captured;
    this.hasMoved = hasMoved;

    this.movePiece = movePiece;
    function movePiece(x, y) {
        // if(isLegal(x, y, this.type){
            // this.x  =  x;
            // this.y  =  y;
        // }
         alert("you moved me!");
    }
}

var whitePawn1  =  piece("white", "pawn", 0, 1, false, false);
var blackBishop1  =  piece("black", "bishop", 8, 3, false, false);

3
具体的JSLint提示是什么? - Aaron Kurtzhals
4个回答

6

您需要将 piece 函数作为构造函数使用,也就是使用 new 关键字调用它。

当前的情况是,函数内部的 this 指向全局对象。基本上,你没有创建新对象并向其中添加属性,反而是向全局对象添加了垃圾信息。

由于您使用了严格模式,this 将会是未定义的,因此您的代码会出现错误。

这是您想要的:

function Piece(color, type, x, y, captured, hasMoved) {
    "use strict";
    this.color = color;
    this.type = type;
    //...

var whitePawn1  = new Piece("white", "pawn", 0, 1, false, false);
var blackBishop1  = new Piece("black", "bishop", 8, 3, false, false);

请注意,我将piece重命名为大写字母开头,因为按照惯例构造函数应该这样做。
此外,假设您确实需要像这样的构造函数,与Ian的答案相比,您应该考虑将movePiece函数移到函数的原型中,这样每次创建新的棋子时就不必重新创建函数了。 因此,代码应该是:
this.movePiece = movePiece;
function movePiece(x, y) {
   //...
}

将会变成这样

//this goes **outside** of your function
Piece.prototype.movePiece = function movePiece(x, y) {
       //...
}

1
我认为在严格模式下,除非通过对象调用函数,否则this将是未定义的。(即:它不再默认为全局对象。) - cHao
@cHao - 是的,但是我认为我说得没错,函数必须在严格模式下定义。如果你只是在函数内部说"use strict",那么这仍然像平常一样是window。 - Adam Rackis
哦,它必须在严格模式脚本内部吗? - cHao
@cHao - 噢,我又测试了一遍。我错了。正在更新我的答案。 - Adam Rackis

1

我不确定在内部/功能上有何不同,但你可以使用:

function piece(color, type, x, y, captured, hasMoved) {
    "use strict";
    return {
        color: color,
        type: type,
        x: x,
        y: y,
        captured: captured,
        hasMoved: hasMoved
    };
}

var whitePawn1 = piece("white", "pawn", 0, 1, false, false);

不需要使用thisnew

尽管我猜您不能使用.prototype将共享属性/方法应用于所有实例。而且返回的对象初始化也是额外的。


1

谢谢Adam Rackis。这就是解决方法。以下是我的最终经过JSLint验证的代码供参考:

function Piece(color, type, x, y, captured, hasMoved) {
    "use strict";
    this.color = color;
    this.type = type;
    this.x = x;
    this.y = y;
    this.captured = captured;
    this.hasMoved = hasMoved;
}
Piece.prototype.movePiece = function movePiece(x, y) {
    "use strict";
    /*global alert */
    alert("you moved me to " + x + ", " + y + "!");
};
var whitePawn1  =  new Piece("white", "pawn", 0, 1, false, false);
var blackBishop1  =  new Piece("black", "bishop", 8, 3, false, false);

0

在调用构造函数之前,您缺少new关键字。代码应该像这样:

var whitePawn1    = new piece("white", "pawn", 0, 1, false, false);
var blackBishop1  = new piece("black", "bishop", 8, 3, false, false);

同时,将构造函数命名为大写字母是一个好的模式,在你的案例中是 Piece

解释:如果没有使用 new ,你的构造函数可能会破坏它们被调用的环境。 new 创建新环境并将其绑定到构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接