【发布时间】:2016-06-11 18:46:05
【问题描述】:
尝试为Array 创建一个包装类,通过事件侦听器对其进行增强。以下是它的用法示例:
new Stack(1, 2, 3).on('push', function (length) {
console.log('Length: ' + length + '.');
}).push(4, 5, 6);
这是我的代码 (fiddle):
(function(window, undefined) {
window.Stack = function(stack) {
if (!(this instanceof Stack)) {
throw new TypeError('Stack must be called with the `new` keyword.');
} else {
if (stack instanceof Array) {
this.stack = stack;
} else {
Array.prototype.push.apply(this.stack = [], Array.prototype.slice.call(arguments));
}
Array.prototype.push.apply(this, this.stack);
this.length = this.stack.length;
}
};
Stack.prototype = {
events: {
},
on: function(event, callback) {
this.events[event].push(callback);
return this;
},
trigger: function(event, args) {
this.events[event].forEach(function(callback) {
callback.call(this.stack, args);
});
return this;
}
};
'fill pop push reverse shift sort splice unshift concat includes join slice indexOf lastIndexOf forEach every some filter find findIndex reduce'.split(' ').forEach(function(method) {
Stack.prototype.events[method] = [];
Stack.prototype[method] = function() {
return this.trigger(method, this.stack[method].apply(this.stack, this.stack.slice.call(arguments)));
};
});
}(window));
我希望能够在不使用 new 的情况下实例化 Stack,通常我会这样做:
if (!(this instanceof Stack)) {
return new Stack(arguments);
}
但这在这里不起作用,因为我本质上是将arguments(一个伪数组)作为第一个参数传递给...arguments。
我要怎样才能在不使用 new 的情况下调用 Stack?
【问题讨论】:
标签: javascript arrays events