当函数返回某些内容时,new 不发挥任何作用

new doesn't play any role when the function returns something

本文关键字:new 作用 任何 返回 函数      更新时间:2023-09-26
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}

当 f1 有返回值时,

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}

在这种情况下,我将如何访问 B?

通过 new 调用构造函数将创建一个新对象,并且this关键字将分配给这个新对象,最后它默认返回新对象。但是,如果显式使用 return,则可以覆盖此新对象。

关键字"new"首先返回自定义对象。 因此,请尝试以下代码。

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

您可以像这样访问它。

x1[0].b

如果你使用的是jQuery,也许使用'$.extend()'来添加返回的对象。

F2 变为:

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

然后:

new f2() => { b: 2, c: 3 }