实例化没有'new'的类

时间:2016-02-28 19:58:48

标签: javascript arrays events

尝试为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));

我希望能够在不使用Stack的情况下实例化new,通常我会这样做:

if (!(this instanceof Stack)) {
  return new Stack(arguments);
}

但它在这里不起作用,因为我实际上是将arguments(一个伪数组)作为第一个参数传递给... arguments

如何制作它以便我可以在不使用new的情况下调用Stack?

1 个答案:

答案 0 :(得分:2)

您可以使用Object.create创建对象,然后使用.apply()来应用参数。

if (!(this instanceof Stack)) {
  var t = Object.create(Stack.prototype);
  Stack.apply(t, arguments);
  return t
}

我相信ES6允许使用spread运算符传递new的参数集合,但这将涵盖旧版浏览器。

相关问题