new调用到底返回什么

最近在专研js的设计模式,下面是装饰器模式原理。

 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 = tree.getDecorate("BlueBalls");
37    tree = tree.getDecorate("AngelBalls");
38    tree.decorate();

打印结果:

Make sure the tree won\'t fall
red
blue
Angel
第35行 tree返回的是RedBalls函数的一个实例,并继承了Tree,
第36行 BlueBalls继承RedBalls,
...
在我不理解new调用与prototype之前,我是看不懂为何会打印这样的结果,下面的demo是验证new调用函数后返回的是什么。
    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.普通调用

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

 
 

 



 

转载于:https://www.cnblogs.com/dzyBlog/p/5347448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值