[英]How to make Constructor parameters available to prototype functions JavaScript
[英]JavaScript: How to make a prototype function with parameters
這是我第一次使用JavaScript原型,我可以使用一些幫助。
我有一個像
function snakegame(C, C_w, C_h, Ls, spd)
{
// .... bunch of other stuff ...
this.boxCollision = function(A, B)
{
return A.x == B.x && A.y == B.y;
}
// ... bunch of other stuff here too ...
}
我想對boxCollision
函數進行原型設計,即在snakegame
定義它,然后在外部編寫實現。 我試過了
function snakegame(C, C_w, C_h, Ls, spd)
{
// .... bunch of other stuff ...
this.boxCollision(A, B);
// ... bunch of other stuff here too ...
}
snakegame.prototype.boxCollision = function(A, B)
{
return A.x == B.x && A.y == B.y;
}
但這沒用。
我也嘗試為原型編寫this.boxCollision(var, var)
,但這也不起作用。 正確的做法是什么?
您可能想要執行以下操作:
var SnakeGame = function () {
//Constructor code
};
SnakeGame.prototype = new Object(); //Or what ever object you are going to inherit from
SnakeGame.prototype.boxCollision = function() {
//code
};
SnakeGame.prototype.otherFunction = ...
然后使用它執行此操作:
var mySnakeGame = new SnakeGame();
mySnakeGame.boxCollision();
同樣,對您的對象使用大寫也很重要,SnakeGame而不是snakegame。 這是慣例,將幫助您保持直率。
如果您想了解有關JavaScript原型的更多信息,則此站點還提供了更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.