美文网首页
JS——new与return

JS——new与return

作者: 隔壁的UNCLE张 | 来源:发表于2017-03-19 13:50 被阅读0次

默认情况下,函数的返回值为undefined(即没有定义返回值)。
  但是构造函数比较例外,new构造函数在没有return的情况下默认返回新创建的对象。然而,在有return的情况下,如果返回值为基本数据类型(string,number,boolean,undefined,null),那么返回值仍然为新建对象实例。
  只有当定义返回一个非基本数据类型的对象,函数的返回值才为指定的对象。在这种情况下,this值所引用的对象就被丢弃了。

如果指定的返回值是基本数据类型的话,仍然会返回新对象

<script>
    function A(){
        this.x=3;
        return "OK";
    }
    var a = new A();
    console.log(a instanceof A);         //true
    console.log("x" in a);               //true
</script>

如果指定返回对象了的话,被返回的对象就成了指定的对象值。在这种情况下,this值所引用的对象就被丢弃了。

<script>
    function B(){
        this.x=3;
        return Object("OK");
    }
    var b = new B();
    console.log("x" in b);              //false
    console.log(b instanceof B);        //false
    console.log(b instanceof String);   //true
</script>

更直观的例子:

<script>
    function User( name, age){
        this.name = name;
        this.age = age;

    // return;                              // 返回 this
    // return null;                         // 返回 this
    // return this;                         // 返回 this
    // return false;                        // 返回 this
    // return 'hello world';                // 返回 this
    // return 2;                            // 返回 this

    // 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 user=new User("小白",20)
    console.log(user);
</script>

返回值为简单的基本数据类型,而不是一个对象(包括基本类型的对象)的话,那么返回值仍然为新创建的对象。

内容参考:http://blog.sina.com.cn/s/blog_7a8c8ac90101hzrq.html

相关文章

网友评论

      本文标题:JS——new与return

      本文链接:https://www.haomeiwen.com/subject/tdvmnttx.html