JS构造函数中的返回语句 [英] Return Statement in JS Constructors

查看:153
本文介绍了JS构造函数中的返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当它作为一个新对象的构造函数(使用'new'关键字)时,return语句在JavaScript函数体中的效果是什么?

What is the effect of a return statement in the body of JavaScript function when it's used as a constructor for a new object(with 'new' keyword)?

推荐答案

通常 return 只是退出构造函数。但是,如果返回的值是一个Object,它将用作 new 表达式的值。

Usually return simply exits the constructor. However, if the returned value is an Object, it is used as the new expression's value.

/ p>

Consider:

function f() {
   this.x = 1;
   return;
}
alert((new f()).x);

显示1,但

function f() {
   this.x = 1;
   return { x: 2};
}
alert((new f()).x);

显示2。

这篇关于JS构造函数中的返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆