【问题标题】:Instantiating a class without 'new' [duplicate]实例化一个没有“新”的类[重复]
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-01-07
      • 2011-10-24
      • 1970-01-01
      • 2020-01-01
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多