Javascript 未捕获的TyperError,使用原型的新手
我似乎不明白为什么这不起作用 行“this.Sprite_u initialize(playerSpriteSheet);”导致错误“Uncaught TypeError:undefined”不是函数。我在这里使用原型正确吗Javascript 未捕获的TyperError,使用原型的新手,javascript,prototype,easeljs,Javascript,Prototype,Easeljs,我似乎不明白为什么这不起作用 行“this.Sprite_u initialize(playerSpriteSheet);”导致错误“Uncaught TypeError:undefined”不是函数。我在这里使用原型正确吗 function init() { canvas = document.getElementById("canvas"); // Creates the stage stage = new createjs.Stage(canvas);
function init() {
canvas = document.getElementById("canvas");
// Creates the stage
stage = new createjs.Stage(canvas);
// Loads the image for player
imgPlayer.src = "img/player.png";
// Create player and add to stage
player = new Player(imgPlayer,300);
stage.addChild(player);
}
function Player(imgPlayer, x_start,x_end){
this.initialize(imgPlayer,x_start,x_end);
}
Player.prototype = new createjs.Sprite();
Player.prototype.alive = true;
// constructor
Player.prototype.Sprite_initialize = Player.prototype.initialize; //avoid overiding base class
Player.prototype.initialize = function (imgPlayer,x_end){
var playerSpriteSheet = new createjs.SpriteSheet({
// Sprite sheet stuff
images: [imgPlayer],
frames: [
[0,0,26,26], //beginWalk0
[26,0,26,26], //walk0
[52,0,26,26], //walk1
[78,0,26,26], //walk2
[0,26,26,26], //stand0
[26,26,26,26], //stand1
[0,52,28,32], //jump0
],
animations: {
stand:{
frames:[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5],
speed:0.3
},
walk:{
frames:[1,2,3],
next:"walk",
speed:0.3
},
beginWalk:{
frames:[0],
next:"walk",
},
jump:{
frames:[6],
},
}
});
this.Sprite_initialize(playerSpriteSheet);
this.x_end = x_end;
// play stand sequence
//this.gotoAndPlay("stand");
this.isInIdleMode = true;
this.name = "Player";
// 1 = right & -1 = left
this.direction = 1;
}
在JavaScript中设置继承链时,您会遇到一个非常常见的错误 你看到什么时候
Foo.prototype = new Base();
…这可能是错误的(尽管不能保证是错误的),至少在使用普通构造函数时是错误的(还有其他模式)
以下是您可能希望设置播放器的方式:
function Player(imgPlayer, x_start,x_end){
createjs.Sprite.apply(this, arguments); // ** Change
this.initialize(imgPlayer,x_start,x_end);
}
Player.prototype = Object.create(createjs.Sprite.prototype); // ** Change
Player.prototype.constructor = Player; // ** Change
Player.prototype.alive = true;
然后
Player.prototype.initialize = function (imgPlayer,x_end){
// Very likely to want this call unless `createjs.Sprite` does it automatically
createjs.Sprite.prototype.initialize.apply(this, arguments);
// ...your code here...
};
详细描述了一般模式
Object.create
是ES5的一项功能,但如果您必须支持非常旧的引擎(如IE8中的引擎),则可以使用上面使用的单参数版本:
if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "The two-argument version of Object.create cannot be polyfilled.";
}
function ctor() { }
ctor.prototype = proto;
return new ctor; // You can add () if you like, they're unnecessary, `new` calls the function
};
}
尝试放置Player.prototype.Sprite\u initialize=Player.prototype.initialize代码>在Player.prototype.initialize之后
谢谢!我已经把它整理好了!为帮助干杯:D