码迷,mamicode.com
首页 > 其他好文 > 详细

new调用到底返回什么

时间:2016-04-02 13:37:42      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

最近在学习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调用到底返回什么

标签:

原文地址:http://www.cnblogs.com/dzyBlog/p/5347448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!