如何在setTile
范围之外调用TopDownGame
函数?我尝试了TopDownGame.Lesson31.setTile(x,y)
,但没有用。
var TopDownGame = TopDownGame || {};
TopDownGame.Lesson31 = function() {};
TopDownGame.Lesson31.prototype = {
setTile: function(x, y) {
console.log(tile);
}
};
答案 0 :(得分:5)
如果已添加到原型,则必须创建对象的 instance 来调用方法:
var TopDownGame = TopDownGame || {};
TopDownGame.Lesson31 = function() {};
TopDownGame.Lesson31.prototype = {
setTile: function(x, y) {
console.log("setTile invoked");
},
};
var instance = new TopDownGame.Lesson31();
instance.setTile(3, 4);
您正在尝试像静态方法那样调用它。如果您确实要这样做,则将方法定义为函数的属性,而不是原型的属性。
TopDownGame.Lesson31 = function() {};
TopDownGame.Lesson31.staticMethod = function() {
console.log('Static method invoked');
}
TopDownGame.Lesson31.staticMethod();
但是,如果您确实想保留setTile
作为原型方法,但仍然调用它,则可以使用apply
方法。
var TopDownGame = TopDownGame || {};
TopDownGame.Lesson31 = function() {};
TopDownGame.Lesson31.prototype = {
setTile: function(x, y) {
console.log(`setTile invoked, this='${this}', x=${x}, y=${y}`);
},
};
new TopDownGame.Lesson31().setTile(3, 4);
TopDownGame.prototype.setTile.apply('actually a string', [5, 6]);
这将导致:
setTile invoked, this='[object Object]', x=3, y=4
setTile invoked, this='actually a string', x=5, y=7