【发布时间】:2019-09-13 19:36:40
【问题描述】:
我有一个打算与new 构造函数一起使用的函数。它应该返回一个值为["Hello World"] 的数组,并包含函数作为方法。这是一个示例/演示(对不起,如果它有点难看):
var my_object = function () {
this.foo = function (data) { // alert and add new item
alert(data);
this.push(data);
};
this.bar = function () { // alert and remove last item
alert(this.pop());
};
this.baz = function (stuff) { // replace last item by running previous methods
this.bar();
this.foo(stuff);
};
var a = "Hello World";
return [a];
};
var arr = new my_object(); // ["Hello World"]
正如预期的那样,arr 的值为["Hello World"]。但是,以下代码会产生错误:
arr.foo('some-text'); // "TypeError: arr.foo is not a function"
其他两个函数出现相同类型的错误。在不更改 Array.prototype、在函数外部创建方法或删除使用 new my_object() 初始化的能力的情况下,我能做些什么来完成这项工作?
注意:如果可能,请不要包含使用 jQuery 或其他外部库的答案。
【问题讨论】:
-
this不是您从函数返回的值,因此您声明的任何方法都将被丢弃而不使用。 -
因为你返回一个数组,..数组没有名为'foo'的方法
-
所以你想从数组继承并添加新方法?
-
这背后的设计理念是什么?
Arrays是类型。您正在使用具有面向对象方法的函数,但要从中返回一个数组。 -
这可能对 OP 有所帮助 -> github.com/wesbos/es6-articles/blob/master/…
标签: javascript arrays function object methods