Reputation: 87
Console said
Uncaught TypeError: Game.start is not a function.
JS:
window.onload = function () {
let socket = io();
function Game() {
let self = this;
}
Game.prototype.start = function () {
alert("something");
}
socket.on("ready", function (data) {
Game.start();
console.log("this console.log is work");
});
}
What is wrong?
Upvotes: 0
Views: 44
Reputation: 4834
Keep scope by using => instead of function.
socket.on("ready", data => {
Game.start();
console.log("this console.log is work");
});
Upvotes: 0
Reputation: 138457
Game.prototype.start()
or
(new Game()).start();
Some explanations: Game will look like this:
Game={
prototype:{
start:function(){}
}
}
So Game.start() wont work as theres no start in Game. If you do new Game it creates an instance that inherits from Game.prototype. Therefore you can call start on that instance. If you wanna call some other functions on that game instance you might store it in a variable
mygameinstance = new Game;
mygameinstance.start();
mygameinstance.dosomeweirdstuff();
I think you havent had a deeper look into inheritance ...
Upvotes: 1