从构造函数返回什么? [英] What is returned from a constructor?
问题描述
如果我在构造函数中返回一些值或对象,那么var会得到什么?
function MyConstroctor()
{
//返回5时的情况;
//返回someObject时的情况;
}
var n = new MyConstroctor();
两种情况下会得到什么?
<实际上它是一个测验问题,答案是什么?
从自定义对象构造函数返回什么?
a)新实例化的对象
b )undefined - 构造函数不返回值
c)返回语句是什么?
d)返回语句是什么;新实例化的对象,如果没有返回语句
我找到了这个很棒的链接:
上面提到的第二个魔法是$ b的能力$ b构造函数返回一个特定的,可能是预先存在的对象,而不是
,而不是对新实例的引用。如果需要,这将允许您自己管理
数量的实际实例;可能出于
有限资源或诸如此类的原因。
var g_deebee = new Deebee ();
函数Deebee(){return g_deebee; }
var db1 = new Deebee();
var db2 = new Deebee();
if(db1!= db2)
throw Error(JS构造函数返回错误的对象!);
If I return some value or object in constructor function, what will the var get?
function MyConstroctor()
{
//what in case when return 5;
//what in case when return someObject;
}
var n = new MyConstroctor();
what n will get in both cases?
Actually its a quiz question, what will be the answer?
What is returned from a custom object constructor?
a)The newly-instantiated object
b)undefined - constructors do not return values
c)Whatever is the return statement
d)Whatever is the return statement; the newly-instantiated object if no return statement
I found this great link:
JavaScript: Constructor Return Value
The second piece of magic eluded to above is the ability for a constructor to return a specific, possibly pre-existing object, rather than a reference to a new instance. This would allow you to manage the number of actual instances yourself if needed; possibly for reasons of limited resources or whatnot.
var g_deebee = new Deebee();
function Deebee() { return g_deebee; }
var db1 = new Deebee();
var db2 = new Deebee();
if (db1 != db2)
throw Error("JS constructor returned wrong object!");
这篇关于从构造函数返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!