[英]JS OOP outside prototype function call ( scope )
我是OOP的新手,我正在編寫一個簡單的游戲腳本來學習OOP原理。
//main game function
battleLevel.prototype =
{
battle:function () {
this.obj1 = {
enterMonsterMenu: function() {
return console.log('enterMonsterMenu');
}
};
},
} /* end OOP prototype */
//external contructor
var Hero = function (warpX, warpY, game, name, life, mana, speed) {
//some code
};
Hero.prototype.monsterSelectUp = function() {
console.log('monsterSelectUp');
//this.enterMonsterMenu();
battleLevel.prototype.battle.call(obj1);
};
我想通過調用monsterSelectUp()來訪問enterMonsterMenu()方法,但我無法正確調用它。 我做錯了什么?
看起來你沒有把這些概念弄好,試着重新閱讀至少這個簡短的介紹 。
讓我們試着看看你試圖稱之為“enterMonsterMenu”的行中會發生什么。 這里是:
battleLevel.prototype.battle.call(obj1);
battleLevel.prototype
是您首先定義的對象。 battleLevel.prototype.battle
是一個函數,你執行它的“調用”方法(因為函數也是js中的對象,並具有像“call”這樣的函數)。
什么是“function.call” 方法 ? 它調用給定函數this
值。 例如,
var myObject = { name: "Object 1" }; var yourObject = { name: "Object 2" }; function test() { alert(this.name); } test.call(myObject); //alert Object 1 test.call(yourObject); //alert Object 2
在您的代碼中,您嘗試調用battleLevel.prototype.battle
並將obj1
作為this
傳遞。
但是在那個代碼點上沒有定義obj1
變量,所以你只需用未定義的變量調用battle
方法。
而且,即使您傳遞了已定義的變量,也無論如何都不會調用enterMonsterMenu
函數。 因為您的方法只將obj1
屬性添加this
對象:
battleLevel = {} battleLevel.prototype = { battle:function () { this.obj1 = { enterMonsterMenu: function() { alert('enterMonsterMenu'); } }; }, } var myThis = {"property": "value"}; alert(JSON.stringify(myThis)); // {"property": "value"}; // This call will add "obj1" property to myThis battleLevel.prototype.battle.call(myThis); alert(JSON.stringify(myThis)); // {"property": "value", "obj1": {}}; // now call the 'enterMonsterMenu' myThis.obj1.enterMonsterMenu();
您可以在上面看到如何實際調用您的enterMonsterMenu
,但說實話,我認為做這樣的事情毫無意義。 而且,正如我所說,你可能需要花更多的時間來學習這些概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.