我今天寫了一個簡單的回調處理程序,作爲我如何進行深層嵌套的示例。我很抱歉,如果不是代碼風格的蜜蜂跪下,它會讓我的概念更清晰一些。
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對函數有一種非正統的方法,但我可以完全明白它爲什麼如此強大。 –