JSLint严格违规.面向对象的Javascript挫折

Cap*_*ack 3 javascript jslint strict use-strict

我正在努力学习在JavaScript中进行面向对象编程并严格违反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;

    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);
Run Code Online (Sandbox Code Playgroud)

Ada*_*kis 6

您需要将您的piece函数用作构造函数 - 换句话说,使用new关键字调用它.

就目前而言,this函数内部是全局对象.基本上,你不是创建一个新对象,而是为它添加属性,而是用垃圾破坏gobal对象.

由于您处于严格模式,因此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);
Run Code Online (Sandbox Code Playgroud)

请注意,我重命名为piece以大写字母开头,因为按照惯例的构造函数应该是.


另外,假设这样的构造函数真的是你想要的,与Ian的答案相比,你应该考虑将movePiece函数移到函数的原型中,这样就不必每次创建函数时都重新创建函数.新作品.所以这

this.movePiece = movePiece;
function movePiece(x, y) {
   //...
}
Run Code Online (Sandbox Code Playgroud)

会成为这个

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