【问题标题】:Return from a javascript function when using NEW [duplicate]使用 NEW [重复] 时从 javascript 函数返回
【发布时间】:2016-03-05 09:11:20
【问题描述】:

我在 java 脚本中遇到了一个有趣的情况,我无法理解:

考虑以下函数:

T = function(){
this.help = 'foo';

var n = function(){};
return 'test';
}

t = new T();时,t是一个实例对象,返回参数被忽略。

但是,写的时候

T = function(){
this.help = 'foo';

var n = function(){};
return n;
}

写入t = new T(); 将导致t 成为function,而不是对象。所以返回值不会被忽略,this 部分会被忽略(分配局部变量)

所以我的两个问题:

  1. 为什么?
  2. 还有其他情况会发生这种情况吗?

【问题讨论】:

    标签: javascript function object constructor


    【解决方案1】:

    当您从“构造函数”(您使用new 调用的任何函数)返回对象 时,该对象将成为返回值。任何其他返回值都将被忽略,并返回新构造的对象。

    文字字符串不是对象,而是函数。

    【讨论】:

      【解决方案2】:

      来自Mozilla JavaScript Reference

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

      简单来说,这就是构造函数调用在 JavaScript 中的工作方式,即如果您返回 nothing原始类型(如普通的 stringnumbers)或 this,则它们将被忽略,最终将返回 this。但是,如果您从构造函数返回一个对象或函数,该对象将返回 new

      我从这个blog post借用了以下代码,在这里可能会有所帮助。

      // Undefined return value.
      function A() {
          return;
        }
        // Reference to instance.
      
      function B() {
          return (this);
        }
        // String return value.
      
      function C() {
          return ("string");
        }
        // Number retun value.
      
      function D() {
          return (123);
        }
        // New object return value.
      
      function E() {
          return ({
            foo: "bar"
          });
        }
        // New array return value.
      
      function F() {
          return (["foo", "bar"]);
        }
        // New instantiation return value.
      
      function G() {
          return (new A());
        }
        // Native "object" return value -- this one would be the same
        // for Number, Boolean, and String.
      
      function H() {
          return (new Number(123));
        }
        // -------------------------------------------------- //
        // -------------------------------------------------- //
        // See what reference we have as a result of instantiation.
      
      console.log(new A());
      console.log(new B());
      console.log(new C());
      console.log(new D());
      console.log(new E());
      console.log(new F());
      console.log(new G());
      console.log(new H());
      

      返回

      A {}
      B {}
      C {}
      D {}
      Object { foo="bar"}
      ["foo", "bar"]
      A {}
      Number {}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-28
        • 2014-06-03
        • 2015-08-01
        • 1970-01-01
        • 2013-10-23
        • 2013-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多