JSLint严格违规.面向对象的Javascript挫折
作者:互联网
我正在努力学习在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);
解决方法:
您需要使用您的piece函数作为构造函数 – 换句话说,使用new关键字调用它.
就目前而言,函数内部是全局对象.基本上,你不是创建一个新对象,而是为它添加属性,而是用垃圾破坏gobal对象.
由于您处于严格模式,因此未定义,因此您的代码将会出错.
这就是你想要的:
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) {
//...
}
标签:javascript,jslint,strict,use-strict 来源: https://codeday.me/bug/20190725/1534852.html