Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 新的';当函数返回某些内容时,不能扮演任何角色_Javascript - Fatal编程技术网

Javascript 新的';当函数返回某些内容时,不能扮演任何角色

Javascript 新的';当函数返回某些内容时,不能扮演任何角色,javascript,Javascript,当f1有返回值时 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} 在这种情况下如何访问b?通过new调用构造函数将创建一个新对象,并且此关键字

当f1有返回值时

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}

在这种情况下如何访问b?

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

如果使用jQuery,则可以使用“”添加返回的对象

f2变成:

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}
然后:


关键字“new”首先返回自定义对象。请尝试以下代码

new f2() => { b: 2, c: 3 }
你可以像这样访问它

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

创建全局对象并将值推入其中…为什么要这样做?很明显,在第二段代码中返回的是一个完全不同的对象。返回
this
或完全忽略return语句。在这种情况下,您无法访问
b
。而且,
new
确实起到了巨大的作用。它创建了一个新的实例,以及一个原本不存在的链接。这很有意义。返回值/对象时,将覆盖默认行为。
function f2(){
  console.log("inside f2");
  this.b = 2;
  return [ this, { c :3 }];
};
var x1 = new f2();
x1[0].b