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

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

问题描述

当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?

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.

考虑:

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天全站免登陆