js-new构造函数中的return

js-new构造函数中的return


javascript 构造函数 new

默认情况下,没有 return 的函数的返回值为 undefined(即没有定义返回值),如果定义了 return,则返回指定对象。 但是构造函数比较特殊,new 构造函数在没有 return 的情况下默认返回新创建的对象。在有 return 的情况下,需要分为两个情况考虑:

如果返回值为基本数据类型(string,number,boolean,undefined,null),那么返回值为新建对象实例,即 this。
var a = function S() {
  this.x = 3;
  return 1;
};
var b = new a();
console.log(a); //{x:3}
如果返回值为一个非基本数据类型的对象,函数的返回值为指定的对象,this 值所引用的对象被丢弃。
var a = function S() {
  this.x = 3;
  return a;
};
var b = new a();
console.log(b); //S(){this.x=3;return a }
直观举例:
var a = function User(name, age) {
  this.name = name;
  this.age = age;

  // return;                              // 返回 this
  // return null;                         // 返回 this
  // return this;                         // 返回 this
  // return true;                        // 返回 this
  // return 'string';                     // 返回 this
  // return 1;                            // 返回 this
  // 以上都返回{name:"哈哈",age:18}
  // return [];                            // 返回 新建的 []
  // return function(){};                  // 返回 新建的 function,抛弃 this
  // return new Boolean( false);           // 返回 新建的 boolean,抛弃 this
  // return new String( 'hello world');    // 返回 新建的 string,抛弃 this
  // return new Number( 32);               // 返回新的 number,抛弃 this
};
var b = new a("哈哈", 18);
console.log(b);
© 2025 Niko Xie