Javascript 从构造函数返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3350215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is returned from a constructor?
提问by coure2011
If I return some value or object in constructor function, what will the var get?
如果我在构造函数中返回一些值或对象,var 会得到什么?
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?
在这两种情况下,n 会得到什么?
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
其实这是一道问答题,答案是什么?
自定义对象构造函数返回什么?
a) 新实例化的对象
b) 未定义 - 构造函数不返回值
c) 无论是什么 return 语句
d) 无论是什么 return 语句;如果没有返回语句,则为新实例化的对象
采纳答案by Haim Evgi
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!");
回答by Triptych
Short Answer
简答
The constructor returns the thisobject.
构造函数返回 this对象。
function Car() {
this.num_wheels = 4;
}
// car = { num_wheels:4 };
var car = new Car();
Long Answer
长答案
By the Javascript spec, when a function is invoked with new, Javascript creates a new object, then sets the "constructor" property of that object to the function invoked, and finally assigns that object to the name this. You then have access to the thisobject from the body of the function.
根据 Javascript 规范,当使用 调用函数时new,Javascript 创建一个新对象,然后将该对象的“构造函数”属性设置为调用的函数,最后将该对象分配给 name this。然后,您可以this从函数体访问该对象。
Once the function body is executed, Javascript will return:
一旦函数体被执行,Javascript 将返回:
ANY object if the type of the returned value is object:
ANY 对象,如果返回值的类型是object:
function Car(){
this.num_wheels = 4;
return { num_wheels:37 };
}
var car = new Car();
alert(car.num_wheels); // 37
The thisobject if the function has no returnstatement OR if the function returns a value of a type other than object:
的this对象,如果函数没有return声明,或如果函数返回以外的其他类型比的值object:
function Car() {
this.num_wheels = 4;
return 'VROOM';
}
var car = new Car();
alert(car.num_wheels); // 4
alert(Car()); // No 'new', so the alert will show 'VROOM'
回答by CMS
Basically if your constructor returns a primitive value, such as a string, number, boolean, null or undefined, (or you don't return anything which is equivalent to returning undefined), a newly created object that inherits from the constructor's prototypewill be returned.
基本上,如果您的构造函数返回一个原始值,例如字符串、数字、布尔值、null 或未定义(或者您不返回任何等效于返回的值undefined),prototype则将返回一个从构造函数继承的新创建的对象。
That's the object you have access with the thiskeyword inside the constructor when called with the newkeyword.
this当使用new关键字调用时,您可以在构造函数中使用关键字访问该对象。
For example:
例如:
function Test() {
return 5; // returning a primitive
}
var obj = new Test();
obj == 5; // false
obj instanceof Test; // true, it inherits from Test.prototype
Test.prototype.isPrototypeOf(obj); // true
But if the returned value is an object reference, that will be the returned value, e.g.:
但是如果返回值是一个对象引用,那将是返回值,例如:
function Test2() {
this.foo = ""; // the object referred by `this` will be lost...
return {foo: 'bar'};
}
var obj = new Test2();
obj.foo; // "bar"
If you are interested on the internals of the newoperator, you can check the algorithm of the [[Construct]]internal operation, is the one responsible of creating the new object that inherits from the constructor's prototype, and to decide what to return:
如果您对new操作符的内部结构感兴趣,您可以检查[[Construct]]内部操作的算法,它负责创建从构造函数原型继承的新对象,并决定返回什么:
When the [[Construct]]internal method for a Functionobject Fis called with a possibly empty list of arguments, the following steps are taken:
当使用可能为空的参数列表调用对象的[[Construct]]内部方法时,将执行以下步骤:FunctionF
- Let
objbe a newly created native ECMAScript object. - Set all the internal methods of
objas specified in 8.12. - Set the
[[Class]]internal property ofobjto"Object". - Set the
[[Extensible]]internal property ofobjtotrue. - Let proto be the value of calling the
[[Get]]internal property ofFwith argument"prototype". - If
Type(proto)is Object, set the[[Prototype]]` internal property of obj to proto. - If
Type(proto)is not Object, set the[[Prototype]]internal property of obj to the standard built-in Object prototype object as described in 15.2.4. - Let result be the result of calling the
[[Call]] internal property of F, providing obj as the this value and providing the argument list passed into[[Construct]]as args. - If
Type(result)is Object then return result. - Return
obj.
- 让
obj成为一个新创建的原生 ECMAScript 对象。 - 设置
obj8.12 中指定的所有内部方法。 - 将
[[Class]]内部属性设置obj为"Object"。 - 将
[[Extensible]]内部属性设置obj为true。 - 令 proto 为调用with argument的
[[Get]]内部属性的值。F"prototype" - 如果
Type(proto)是 Object, set the[[Prototype]]` obj 到 proto 的内部属性。 - 如果
Type(proto)不是Object,则将[[Prototype]]obj的内部属性设置为15.2.4中描述的标准内置Object原型对象。 - 令 result 是调用
[[Call]F的] 内部属性的结果,提供 obj 作为 this 值并提供[[Construct]]作为 args传入的参数列表。 - 如果
Type(result)是 Object 则返回结果。 - 返回
obj。
回答by Fenton
To answer your specific question:
要回答您的具体问题:
function MyConstructor()
{
return 5;
}
var n = new MyConstructor();
n is an object instance of MyConstructor.
n 是 MyConstructor 的对象实例。
function SomeObject(name) {
this.name = name;
this.shout = function() {
alert("Hello " + this.name)
}
}
function MyConstructor()
{
return new SomeObject("coure06");
}
var n = new MyConstructor();
n.shout();
n is an instance of SomeObject (call n.shout() to prove it)
n 是 SomeObject 的一个实例(调用 n.shout() 来证明)
To make this all absolutely clear...
为了让这一切完全清楚......
1) If you return a primitive type, like a number or a string, it will be ignored. 2) Otherwise, you will pass back the object
1) 如果您返回原始类型,如数字或字符串,它将被忽略。2)否则,您将传回对象
Functions and constructors are exactly the same in JavaScript, but how you call them changes their behaviour. A quick example of this is below...
JavaScript 中的函数和构造函数完全相同,但是您如何调用它们会改变它们的行为。下面是一个简单的例子......
function AddTwoNumbers(first, second) {
return first + second;
}
var functionCall = AddTwoNumbers(5, 3);
alert(functionCall);// 8
var constructorCall = new AddTwoNumbers(5, 3);
alert(constructorCall);// object
回答by Philipp Munin
It's as easy as it said in documentation (new operator):
就像文档(新运算符)中所说的一样简单:
The object returned by the constructor function becomes the result of the whole
newexpression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
构造函数返回的对象成为整个
new表达式的结果。如果构造函数没有显式返回对象,则使用在步骤 1 中创建的对象。(通常构造函数不返回值,但如果他们想覆盖正常的对象创建过程,他们可以选择这样做。)
回答by Marinos An
Trying to simplify the existing answers by providing concrete examples.
试图通过提供具体的例子来简化现有的答案。
Consider the following constructor that returns exactly what we pass to it:
考虑以下构造函数,它返回我们传递给它的内容:
//A constructor returning the passed value, or not returning at all.
function MyConstructor(obj){
if(obj!==undefined){
return obj;
}
//else do not call return
}
//no value passed (no value is returned from constructor)
console.log((new MyConstructor()) instanceof MyConstructor)
//true
//Primitive passed:
console.log((new MyConstructor(1)) instanceof MyConstructor)
//true
console.log((new MyConstructor("1")) instanceof MyConstructor)
//true
console.log((new MyConstructor("1")) instanceof MyConstructor)
//true
console.log((new MyConstructor(1.0)) instanceof MyConstructor)
//true
//Object passed
console.log((new Number(1)) instanceof MyConstructor)
//false
console.log((new MyConstructor({num:1})) instanceof MyConstructor)
//false
console.log((new MyConstructor([1])) instanceof MyConstructor)
//false
console.log((new MyConstructor(MyConstructor)) instanceof MyConstructor)
//false
//Same results if we use: MyConstructor.prototype.isPrototypeOf(new MyConstructor()) e.t.c..
The same rulesas above apply also for class constructors. This means we can have:
在同样的规则与上述同样适用于类构造函数。这意味着我们可以:
(new MyClass()) instanceof MyClass //false
Additional note:Sometimes a function could act as a constructor even if it is not called as a constructor:
附加说明:有时即使函数不是作为构造函数调用,它也可以充当构造函数:
function F(){
//If not called as a constructor, call as a constructor and return the result
if(!new.target){
return new F();
}
}
console.log(F() instanceof F)
//true
console.log(new F() instanceof F)
//true
回答by Darin Dimitrov
You shouldn't return anything in a constructor. A constructor is used to initialize the object. In case you want to know what happens is that if you return 5then nwill simply be an empty object and if you return for example { a: 5 }, then nwill have a property a=5.
你不应该在构造函数中返回任何东西。构造函数用于初始化对象。如果您想知道会发生什么,如果您返回,5那么n将只是一个空对象,例如{ a: 5 },如果您返回,n则将有一个属性a=5。

