如何调用存储在正在用作另一个函数参数的对象中的函数?
问题描述:
我会说实话,我正在用这一个在我的头上。任何帮助,将不胜感激。如何调用存储在正在用作另一个函数参数的对象中的函数?
目的
我想打电话给一个叫重启功能,但该功能是一个对象内,被传递给函数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
没有biggy我没有想到它的工作。 基于这个问题> 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.
所以我的问题。
如何调用重启功能?
CODE为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;
};
答
你出现在约翰Resig的例子here要立足这一点,你应该看看他是怎么做的:)
Class.extend返回一个构造函数一类。你可以创建一个类的实例,然后调用它。
你需要的东西,如:
var chicken = new Chickenz();
chicken.restart();
注意,这将立即抛出一个错误,现在虽然,因为this
将被绑定到新的鸡对象,鸡不具有score.restart
功能除非你有其他的代码,你没有向我们展示。我不知道你想要那行代码做什么,但是你需要添加一个带有重新启动方法的score属性给这个鸡对象,或者让restart
方法引用别的东西。
谢谢!我还没有工作,但这绝对是正确的轨道。 – TryHarder 2013-04-07 03:14:18