如何在JavaScript原型之外调用函数?

时间:2018-10-08 06:32:36

标签: javascript prototype

如何在setTile范围之外调用TopDownGame函数?我尝试了TopDownGame.Lesson31.setTile(x,y),但没有用。

var TopDownGame = TopDownGame || {};

TopDownGame.Lesson31 = function() {};

TopDownGame.Lesson31.prototype = {
    setTile: function(x, y) {
        console.log(tile);
    }
};

1 个答案:

答案 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