简体   繁体   中英

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 ? I tried TopDownGame.Lesson31.setTile(x,y) , but it doesn't work.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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