ES6 中的方法原型



我想用ES6写这个,但是我被困住了,需要你的帮助。 当我使用 ES6 时,确实声明了我的方法,方法原型给了我这个错误:

捕获的类型错误:无法在平面上设置未定义的属性"移动"JS.js:238

let SI = {};
//some SI.Properties that i need...
// SI.SpaceShip = function (options) { // works fine
SI.SpaceShip = (options) => { // gives error
let defaultOptions = {
x: 0,
y: 0,
width: 0,
height: 0,
img: null,
imgX: 0, 
}
for (let key in defaultOptions) {
if(options.hasOwnProperty(key)) {
this[key] = options[key];
}
else {
this[key] = defaultOptions[key];
}
}
}

这是原型:

SI.SpaceShip.prototype.move = function (deltaX, deltaY) {
this.x += deltaX;
if(this.x <= 0) {
this.x = 0;
}
else if(this.x >= SI.Sizes.width - this.width) {
this.x = SI.Sizes.width - this.width;
}
this.y += deltaY;
if(this.y <= 0) {
this.y = 0;
}
else if(this.y >= SI.Sizes.height - this.height) {
this.x = SI.Sizes.height - this.height;
}
}

箭头函数没有原型,不能用作对象构造函数。参见 MDN

箭头函数表达式 [...] 没有自己的这个, 参数、super 或new.target。这些函数表达式最适合非方法函数,不能用作构造函数

你可以这样修复它

SI.SpaceShip = function (options) { ...

最新更新