2012-02-21 61 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