简体   繁体   English

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

[英]How can I call a function outside of the prototype in JavaScript?

How can I call the setTile function outside of the scope of TopDownGame ? 我如何可以调用setTile范围之外的功能TopDownGame I tried TopDownGame.Lesson31.setTile(x,y) , but it doesn't work. 我尝试了TopDownGame.Lesson31.setTile(x,y) ,但是它不起作用。

var TopDownGame = TopDownGame || {};

TopDownGame.Lesson31 = function() {};

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

If you have added to the prototype, then you must create an instance of the object to invoke a method: 如果已添加到原型,则必须创建对象的实例以调用方法:

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);

You were trying to invoke it like it was a static method. 您试图像静态方法那样调用它。 If that's what you really want to do, define the method as a property of the function, not of the prototype. 如果那是您真正想要做的,则将方法定义为函数的属性,而不是原型的属性。

TopDownGame.Lesson31 = function() {};
TopDownGame.Lesson31.staticMethod = function() {
    console.log('Static method invoked');
}

TopDownGame.Lesson31.staticMethod();

But if you really want to keep setTile as a prototype method, but still invoke it, you can use the apply method. 但是,如果您确实希望将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]);

This will result in: 这将导致:

setTile invoked, this='[object Object]', x=3, y=4
setTile invoked, this='actually a string', x=5, y=7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM