2012-02-21 43 views
0

http://jsfiddle.net/ryanneufeld/Y8ZNU/我該如何將其轉換爲Array原型的擴展?

在這個例子中,我創建了一個隊列模型,我假設谷歌正在處理分析事件。事情是我想將它轉換爲數組原型的擴展。

我想要完成的是,當你創建一個Queue的新實例並傳入一個隊列數組時,新實例將作爲一個數組來添加額外的功能。

+1

[這是不太可能在JavaScript中創建自己的Array子類](http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/)。 – Pointy 2012-02-21 18:27:56

回答

0
function log() { 
    /* workaround for chrome not playing nice and letting me .apply to console */ 
    console.log.apply(console, arguments); 
} 

var q = q || [[log, 'first item q1']], 
    q2 = q2 || [[log, 'first time q2']]; 

// You'll want a console open for this. 

function Queue(_q, name) { 
    var _q = _q || [], 
     name = name || 'mlQueue'; 

    function processQueue() { 
     task = _q.shift(); 
     while (task) { 
      func = task.shift(); 
      func.apply(window, task); 
      task = _q.shift(); 
      } 
     } 

     function init() { 
      _q._push = _q.push; 
      processQueue(); 
      _q.push = function() { 
      //first push it to the array 
      _q._push.apply(_q, arguments); 
      processQueue(); 
     }; 
    } 

    function push() { 
     console.log(name + ' pushing values'); 
     _q.push.apply(_q, arguments); 
    }; 

    return { 
     init: init, 
     push: push, 
     run: processQueue, 
     name: name 
    } 
}; 

var q = new Queue(q, 'q1'); 
q.push([log, 'q1 and more']); 
q.init(); 
q.push([log, 'q1 and more']); 

var q2 = new Queue(q2, 'q2'); 
q2.init(); 
q2.push([log, 'q2 and more']);​ 
1

可能並不完美,但它完成這項工作:(見@Pointy在評論一個很好的解釋提供的鏈接,以什麼缺陷是)

function pseudoArray(name) { 

    if (!(this instanceof pseudoArray)) { 
     return new pseudoArray(name); 
    } 

    var self = this; 

    self.name = name || 'defaultName'; 

    var _push = self.push; 
    self.push = function(args) { 
     console.log('"' + name + '" pushing [ ' + Array.prototype.slice.apply(arguments) + ' ]'); 
     _push.apply(self, arguments); 
    }; 

    return self; 

} 

pseudoArray.prototype = []; 

var x = new pseudoArray('fake array'); 

x.push('yay', 77, function() { alert('yup'); }); 
x.push('things'); 
x.push(12); 

console.log(x instanceof Array); 
console.log('to string: ' + x); 
console.log('length: ' + x.length); 
console.log('pop result: ' + x.pop()); 
console.log('length: ' + x.length); 
+0

我想出了最終的解決方案: http://jsfiddle.net/ryanneufeld/Y8ZNU/10/ – ryanneufeld 2012-02-24 22:59:19