如何在保留其方法的同时从新对象返回值

Ric*_*ich 0 javascript

所以我有这样的代码:

function set(a) {
  this.foo = function(){
    alert('bar');
  }

  return a;
}

var b = new set([2,3,4]);

b; //returns [2,3,4]
b.foo(); //undefined function
Run Code Online (Sandbox Code Playgroud)

我想将数组输入作为新集合的返回值返回,而不是必须将其附加到属性,例如 this.arr = a;

如何在不擦除对象的foo方法的情况下实现这一目的?

A h*_*ing 5

我想你可以这样做!

function set(a) {
  a.foo = function(){
    alert('bar');
  }

  return a;
}

var b = new set([2,3,4]);

b; //returns [2,3,4]
b.foo(); //this shows alert
Run Code Online (Sandbox Code Playgroud)