我今天写了一个简单的回调处理程序,作为我如何进行深层嵌套的示例。我很抱歉,如果不是代码风格的蜜蜂跪下,它会让我的概念更清晰一些。
function test() {
this.that = this;
this.root = this;
this.jCallback = new Array(new Array()); // 2d
this.jCallbackCount = -1;
this.str = "hello";
// Callback handler...
this.command = {
that : this, // let's keep a reference to who's above us on the food chain
root : this.root, // takes us back to the main object
// add : function() { var that = this; console.log(that.that.str); },
add : function(targetFnc, newFunc) {
var that = this;
var home = that.that; // pretty much root but left in as an example of chain traversal.
var root = this.root; // useful for climbing back up the function chain
// console.log(that.that.str);
home.jCallbackCount++;
// target, addon, active
home.jCallback[home.jCallback.length] = { 'targetFunc' : targetFnc, 'newFunc' : newFunc, 'active' : true, 'id': home.jCallbackCount};
console.log('cbacklength: ' + home.jCallback.length);
console.log('added callback targetFunction:[' + targetFnc + ']');
return home.jCallbackCount; // if we want to delete this later...
},
run : function(targetFnc) {
var that = this;
var home = that.that;
console.log('running callback check for: ' + targetFnc + ' There is : ' + (home.jCallbackCount + 1) + 'in queue.');
console.log('length of callbacks is ' + home.jCallback.length);
for(i=0;i < home.jCallback.length - 1;i++)
{
console.log('checking array for a matching callback [' + targetFnc + ']...');
console.log('current item: ' + home.jCallback[i]['targetFunc']);
if(home.jCallback[i]['targetFunc'] == targetFnc)
{
// matched!
home.jCallback[i]['newFunc']();
}
// console.log(that.that.jCallback[i].targetFunction);
}
}
};
}
test.prototype = {
say : function() {
var that = this;
console.log('inside');
// that.command('doSay');
that.command.run('doSay');
console.log(that.str);
}
} // end proto
// BEGIN TESTING **************************************************************************
// BEGIN TESTING **************************************************************************
// BEGIN TESTING **************************************************************************
var testing = new test();
testing.command.add('doSay', function() { console.log('213123123'); });
testing.command.add('doSay', function() { console.log('12sad31'); });
testing.command.add('doSay', function() { console.log('asdascccc'); });
testing.say();
直播: http://jsfiddle.net/Ps5Uf/
- 注意:要查看控制台输出,只需打开检查中铬,然后单击 “控制台” 选项卡上。
你想实现什么? – NicoSantangelo
我想模仿通常在编程语言中看到的嵌套类。它使得OOP非常有组织,图书馆更有条理。我知道JavaScript并不是真正为复杂的OOP构建的,但不管它有什么用处。 JavaScript对函数有一种非正统的方法,但我可以完全明白它为什么如此强大。 –