Javascript构造函数返回值 [英] Javascript constructor return values

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

问题描述

考虑以下代码:

function Foo() {
  return "something";
}

var foo = new Foo(); 

根据JavaScript专家的说法,他们说从a返回nothing或者只返回this构造函数。是什么原因?

According to the experts in JavaScript, they say that return "nothing" or just "this" from a constructor. Whats the reason for this?

我知道当使用new时,this会被设置为构造函数的原型对象,但是无法理解仅此一点。

I am aware that when used "new", the "this" would be set to the prototype object of the constructor but not able to understand this point alone.

推荐答案

该特定代码将引发ReferenceError,因为某事未声明。

That particular code will throw a ReferenceError because something is not declared.

您应该返回此或者在构造函数中根本没有return语句,因为否则你将构造一个新的类实例(这个的值,以及默认的返回值),然后扔掉它。

You should either return this or have no return statement at all in a constructor function because otherwise you will have constructed a new instance of the class (the value of this, and the default return value) and then thrown it away.


我知道当使用new时,this将被设置为构造函数的原型对象

I am aware that when used "new", the "this" would be set to the prototype object of the constructor

不正确。它将被设置为构造函数的一个实例。

Incorrect. It will be set to an instance of the constructor.

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

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