Javascript 如何调用存储在对象中的函数,该对象正被用作另一个函数的参数?
老实说,这件事让我有些不知所措。任何帮助都将不胜感激 目标 我想调用一个名为restart的函数,但该函数位于一个对象内部,正在传递给一个函数Javascript 如何调用存储在对象中的函数,该对象正被用作另一个函数的参数?,javascript,jquery,function,object,arguments,Javascript,Jquery,Function,Object,Arguments,老实说,这件事让我有些不知所措。任何帮助都将不胜感激 目标 我想调用一个名为restart的函数,但该函数位于一个对象内部,正在传递给一个函数类。extend 我使用的代码是 var Chickenz = Class.extend( { init: function(value) { //do something }, // restart game restart: function
类。extend
我使用的代码是
var Chickenz = Class.extend(
{
init: function(value)
{
//do something
},
// restart game
restart: function()
{
this.score.restart();
//etc
}
});
我试过什么
restart()代码>不起作用。我得到类型错误:重启不是一个功能
没什么大不了的,我没想到它会工作。
基于这个问题>
我想我可以做一些类似于Chickenz.restart()的事情代码>但由于Class.extend,它更复杂
我已经将Class.extend的代码包含在这个问题的底部
稍后,使用以下代码调用restart函数
/* GUI Events */
// restart button
addEvent($("restart"), "click", function() {
self.restart();
return false;
});
我想我应该试试self.restart()代码>但这不起作用-类型错误:self.restart不是一个函数。
所以我的问题。
如何调用重启函数
类的代码。扩展
var initializing = false;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype,
prototype,
name,
tmp,
ret;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for ( name in prop ) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" ?
(function(name, fn){
return function() {
tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
//Changed according to http://ejohn.org/blog/simple-class-instantiation/
//Use the new operator to instantiation
function Class(args){
if ( this instanceof arguments.callee ) {
if ( !initializing && this.init )
this.init.apply( this, args.callee ? args : arguments );
} else
return new arguments.callee( arguments );
};
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
您似乎是基于John Resig的例子,您应该看看他是如何做到这一点的:)
extend返回类的构造函数。您只需创建该类的一个实例,然后调用它
你需要像这样的东西:
var chicken = new Chickenz();
chicken.restart();
请注意,这将立即抛出一个错误,因为this
将绑定到新的chicken对象,并且chicken没有分数。请重新启动函数,除非您有其他未显示的代码。我不知道您希望该行执行什么操作,但是您需要向chicken对象添加一个带有restart方法的score属性,或者让restart
方法引用其他内容。谢谢!我还没有让它工作,但这绝对是正确的轨道。