new调用到底返回什么

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了new调用到底返回什么相关的知识,希望对你有一定的参考价值。

最近在学习js的设计模式,其中在学习装饰器模式中遇到new调用的问题,一直很疑惑。

 1     var tree = {
 2 
 3        decorate:function(){
 4            alert("Make sure the tree won\‘t fall");
 5        },
 6       
 7        //tree的某个属性,并继承tree
 8        getDecorate:function(deco){
 9               tree[deco].prototype = this;
10            return new tree[deco];
11        },
12 
13        RedBalls:function(){
14          this.decorate = function(){
15             this.RedBalls.prototype.decorate();
16             alert("red");
17          };
18        },
19 
20        BlueBalls:function(){
21          this.decorate = function(){
22             this.BlueBalls.prototype.decorate();
23             alert("blue");
24          };
25        },
26 
27        AngelBalls:function(){
28          this.decorate = function(){
29             this.AngelBalls.prototype.decorate();
30             alert("Angel");
31          };
32        }
33     };
34 
35    tree = tree.getDecorate("RedBalls");
36    tree = a.getDecorate("BlueBalls");
37    tree = a.getDecorate("AngelBalls");
38    tree.decorate();

打印结果:

Make sure the tree won\‘t fall
red
blue
Angel

在我不理解new调用的情况下,我是看不懂为何是打印这样的结果,于是写一个demo。
    function add(m,n){
       alert("执行了我!");
       var result = m+n || 5;
       return result;
    }

    var b = new add;
    alert(b);

执行结果:

执行了我!

[object Object]

耶?怎么会这样??又好像哪里不对,你的new add后面没有加括号,于是我加上括号。

    function add(m,n){
       alert("执行了我!");
       var result = m+n || 5;
       return result;
    }

    var b = new add();
    alert(b);

执行结果:

执行了我!

[object Object]

 

我晕,还是如此! 到底是哪里出问题了呢?还是直接说吧,将代码改造成这样:

    function add(m,n){
       alert("执行了我!");
       var result = m+n || 5;
       return new String(result);
    }

    var b = new add();
    alert(b);

执行结果:
执行了我!
5

... 终于得到我想要的结果了。

 

总结:

1.new 调用时

      加括号与不加括号,都会执行函数代码块,加括号可用于传参。

当函数体返回值为基础数据类型时(如string,number等),则new调用后得到的是一个函数的实例,即Object,除非对基础数据类型作包装(new String,new Number等)

2.普通调用

      这样方式的调用必须加括号,不管函数有无参数。函数返回什么类型则接收到的就是什么类型。


 



 

以上是关于new调用到底返回什么的主要内容,如果未能解决你的问题,请参考以下文章

js中的new()到底做了些什么??

详解 JS 中 new 调用函数原理

javascript 容易忽略的小知识点 new到底做了什么?

js面试-手写代码实现new操作符的功能

Android片段生命周期:onResume调用了两次

安卓。片段 getActivity() 有时返回 null