我會說實話,我正在用這一個在我的頭上。任何幫助,將不勝感激。如何調用存儲在正在用作另一個函數參數的對象中的函數?
目的
我想打電話給一個叫重啓功能,但該功能是一個對象內,被傳遞給函數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;
};
謝謝!我還沒有工作,但這絕對是正確的軌道。 – TryHarder 2013-04-07 03:14:18