1
function f1(){
 console.log("inside f1");
 this.a = 2;
};
var x1 = f1();      => inside f1
x1;                 => undefined
var x1 = new f1();  => inside f1
x1;                 => f1 {a: 2}

When f1 has a return value,

function f2(){
 console.log("inside f2");
 this.b = 2;
 return { c :3 };
};

var x1 = f2();      => inside f2
x1;                 => Object {c: 3}

var x1 = new f2();  => inside f2
x1;                 => Object {c: 3}

how would I access b in this case?

4

3 回答 3

4

Calling a constructor by new will create a new object, and this key word will be assigned to this new object, at last it returns the new object by default. However this new object can be overridden if you use return explicitly.

于 2013-09-14T06:48:38.770 回答
0

The keyword 'new' returns the custom object first. so try following codes, plz..

function f2(){
  console.log("inside f2");
  this.b = 2;
  return [ this, { c :3 }];
};
var x1 = new f2();

You can access it, like this..

x1[0].b
于 2013-12-29T16:48:17.493 回答
-2

If you're using jQuery, perhaps use '$.extend()' to add in the returned object.

f2 becomes:

function f2(){
    this.b = 2;
    $.extend(this, { c: 3 });
};

Then:

new f2() => { b: 2, c: 3 }
于 2013-09-14T06:55:57.820 回答