[英]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.