从构造函数返回什么?

时间:2010-07-28 05:47:17

标签: javascript

如果我在构造函数中返回一些值或对象,var会得到什么?

function MyConstroctor()
{
    //what in case when return 5;
    //what in case when return someObject;
}

var n = new MyConstroctor();

两种情况下会得到什么?

实际上它是一个测验问题,答案是什么? 从自定义对象构造函数返回什么?
a)新实例化的对象
b)undefined - 构造函数不返回值
c)退货声明是什么 d)退货声明是什么;新实例化的对象,如果没有返回语句

7 个答案:

答案 0 :(得分:58)

简答

构造函数返回this对象。

function Car(){
   this.num_wheels = 4;
}

// car = {num_wheels:4};
var car = new Car();

长答案

通过Javascript规范,当使用new调用函数时,Javascript创建一个新对象,然后将该对象的“构造函数”属性设置为调用的函数,最后将该对象分配给名称{ {1}}。然后,您可以访问函数体的this对象。

执行函数体后,Javascript将返回:

任何对象,如果函数手动返回一个:

this

function Car(){ this.num_wheels = 4; return {num_wheels:37}; } var car = new Car(); alert(car.num_wheels); // 37! 对象,如果函数没有this语句或者函数返回的值不是return

object

答案 1 :(得分:35)

基本上,如果构造函数返回原始值,例如字符串,数字,布尔值,空值或未定义,(或者您不返回任何等同于返回undefined的内容),将返回一个从构造函数prototype继承的新创建的对象。

当使用this关键字调用时,这是您在构造函数中使用new关键字访问的对象。

例如:

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

但是如果返回的值是对象引用,那将是返回的值,例如:

function Test2() {
  this.foo = ""; // the object referred by `this` will be lost...
  return {foo: 'bar'};
}

var obj = new Test2();
obj.foo; // "bar"

如果您对new运算符的内部感兴趣,可以检查[[Construct]]内部运算的算法,负责创建从构造函数原型继承的新对象,并决定返回什么:

13.2.2 [[Construct]]

当使用可能为空的参数列表调用[[Construct]]对象Function的{​​{1}}内部方法时,将执行以下步骤:

  1. F成为新创建的本机ECMAScript对象。
  2. 按照8.12中的规定设置obj的所有内部方法。
  3. obj的{​​{1}}内部属性设置为[[Class]]
  4. obj的{​​{1}}内部属性设置为"Object"
  5. 让proto成为使用参数[[Extensible]]调用obj true内部属性的值。
  6. 如果[[Get]]是对象F [[原型]]`obj到proto的内部属性。
  7. 如果"prototype"不是Object,请将obj的Type(proto)内部属性设置为标准内置Object原型对象,如15.2.4中所述。
  8. 让结果成为调用F的, set the]内部属性的结果,提供obj作为此值,并提供传递给Type(proto)的参数列表作为args。
  9. 如果[[Prototype]]是对象,则返回结果。
  10. 返回[[Call]

答案 2 :(得分:19)

我找到了这个很棒的链接:

JavaScript: Constructor Return Value

  

上面提到的第二个魔法是a的能力   构造函数返回一个特定的,可能是预先存在的对象   而不是对新实例的引用。这将允许您管理   如果需要,你自己的实际数量;可能是出于这个原因   有限的资源或诸如此类的。

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!");

答案 3 :(得分:1)

通过提供离散的示例来证明以下事实,以简化现有答案:

只有返回primitiveundefined的构造函数会隐式地创建自己的新实例。否则,将按原样使用构造函数返回的确切对象。

请考虑以下构造函数,该构造函数将精确返回我们传递给它的内容:

//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(false)) 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..

上面的相同规则也适用于类构造函数。这意味着我们可以:

(new MyClass()) instanceof MyClass //false

按原样vs隐式的self的新实例:

//As above
function MyConstructor(obj){
    if(obj!==undefined){
        return obj;
    }
    //else do not call return
}

//Object passed
let obj = {x:0};
let a1 = new MyConstructor(obj)
let a2 = new MyConstructor(obj)

a1.x=1
a2.x=2

console.log(a1.x === a2.x, a1.x, a2.x)
//true 2 2

//Primitive/undefined passed
let b1 = new MyConstructor()
let b2 = new MyConstructor()

b1.x=1
b2.x=2
console.log(b1.x === b2.x, b1.x, b2.x)
//false 1 2


附加说明:有时,即使未将函数称为构造函数,该函数也可以充当构造函数:

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

答案 4 :(得分:0)

您不应该在构造函数中返回任何内容。构造函数用于初始化对象。如果您想知道发生了什么,如果您返回5,那么n将只是一个空对象,如果您返回{ a: 5 },那么n将会有属性a=5

答案 5 :(得分:0)

回答您的具体问题:

function MyConstructor()
{
    return 5;
}
var n = new 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是SomeObject的一个实例(调用n.shout()来证明它)

要使这一切绝对清楚......

1)如果返回基本类型,如数字或字符串,则会被忽略。 2)否则,您将传回对象

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

答案 6 :(得分:0)

它就像documentation (new operator)中所说的一样简单:

  

构造函数返回的对象成为整个new表达式的结果。如果构造函数没有显式返回对象,则使用在步骤1中创建的对象。 (通常构造函数不会返回值,但如果他们想要覆盖正常的对象创建过程,他们可以选择这样做。)