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

问题描述 投票:3回答:4

我正在努力学习在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);
javascript jslint strict use-strict
4个回答
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);

请注意,我将qazxsw poi重命名为以大写字母开头,因为按惯例构造函数应该是。


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

movePiece

会成为这个

this.movePiece = movePiece;
function movePiece(x, y) {
   //...
}

1
投票

我不确定内部/功能会有什么不同,但您可以使用:

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

这不需要使用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); this

虽然我猜你不能使用new将共享属性/方法应用于所有实例。返回的对象初始化也是额外的。


1
投票

啊,谢谢Adam Rackis。这样做了。作为参考,这是我最终的JSLint验证代码:

.prototype

0
投票

在调用构造函数之前,您缺少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); 关键字。代码应如下所示:

new

在你的情况下var whitePawn1 = new piece("white", "pawn", 0, 1, false, false); var blackBishop1 = new piece("black", "bishop", 8, 3, false, false); ,用大写字母命名构造函数也是很好的模式

说明:如果没有Piece,您的构造函数可能会破坏它们所调用的环境。 new创建新环境并将其绑定到构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.