我是 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() 方法,但我无法正确调用它。我做错了什么?
最佳答案
看起来你没有理解正确的概念,至少尝试重新阅读 this short intro .
让我们看看在您尝试调用“enterMonsterMenu”的行中发生了什么。 在这里:
battleLevel.prototype.battle.call(obj1);
battleLevel.prototype
是您首先定义的对象。
battleLevel.prototype.battle
是一个函数,您执行它的“call”方法(因为函数在 js 中也是对象,并且具有类似“call”的功能)。
“function.call”是什么method ?它调用具有给定 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
变量,所以你只需要用 undefined variable 调用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
,但老实说,我认为这样做没有意义。而且,正如我所说,您可能需要花更多时间来学习这些概念。
关于javascript - JS OOP 外部原型(prototype)函数调用(作用域),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785042/