老实说,我对这个问题有点不知所措。任何帮助将不胜感激。
目标
我想调用一个名为 restart 的函数,但该函数位于对象内部,并且正在传递给函数 Class.extend
。
我正在使用的代码是
var Chickenz = Class.extend(
{
init: function(value)
{
//do something
},
// restart game
restart: function()
{
this.score.restart();
//etc
}
});
我尝试了什么?
restart();
不起作用。我得到 TypeError: restart is not a function
没什么大不了的,我没想到它会起作用。
基于这个问题>
Javascript - Storing function in object - bad practice?
我以为我可以做类似 Chickenz.restart();
的事情,但由于 Class.extend
我已经在这个问题的底部添加了 Class.extend 的代码。
稍后使用以下代码调用重启函数
/* GUI Events */
// restart button
addEvent($("restart"), "click", function() {
self.restart();
return false;
});
我想我会尝试 self.restart();
但那不起作用 - TypeError: self.restart is not a function.
所以我的问题。
如何调用重启函数?
Class.extend 的代码
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 的示例 here你应该看看他是怎么做的:)
Class.extend 返回类的构造函数。您只需创建该类的实例然后调用它即可。
你需要这样的东西:
var chicken = new Chickenz();
chicken.restart();
请注意,这会立即引发错误,因为 this
随后将绑定(bind)到新的小鸡对象,而小鸡没有 score.restart
函数,除非您有其他未向我们展示的代码。我不知道您希望该行执行什么操作,但您需要向 Chicken 对象添加一个带有 restart 方法的 Score 属性,或者让 restart
方法引用其他内容。
关于javascript - 如何调用存储在用作另一个函数参数的对象中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15858236/