gpt4 book ai didi

javascript - 实例化一个没有 'new' 的类

转载 作者:行者123 更新时间:2023-11-29 14:43:21 25 4
gpt4 key购买 nike

<分区>

尝试为 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?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com