首页 > 新人求助2个js问题

新人求助2个js问题

1.return "hello"+(who?","+who:"");
这行代码是判断who是否为空吗?没见过这个语法

2.
var type="" function Block(){ this.new=function(){ type=type||"B1"; } this.transform=function(type){ switch(type){ case "B1"://变纵向 type="B2"; break; case "B2"://变横向 type="B1"; break; } } } var b=new Block(); var c=b.new(); var a=b.transform(type); alert(type); b.transform(type); alert(type);
为什么b.transform(type)不能把全局变量中的B1改为B2

这插入代码片段为什么没有格式...


1.是的,括号里面的是一个三元表达式。
2.js调用方法传参是值传递,即b.transform(type)实际传进去的是type的值"B1",在transform()方法内部的type变量的值才会改变。如果楼主想达到改变全局type的值的效果,可以将transform方法的定义改为无参数。


直接贴代码吧,希望能看懂。希望以后发问题时代码能够整理下吧

1.

var a = who ? who : '';
return "hello"+a;

2.

var type="" ;
function Block(){ 
    this.new = function(){ 
        type = type || "B1"; 
    };
    this.transform = function(arg){ 
        switch(arg){ 
            case "B1"://变纵向 
            arg= "B2"; 
            break; 
            case "B2"://变横向 
            arg= "B1"; 
            break; 
        } 
      type = arg;
    };
} 
var b = new Block(); 
var c = b.new(); 
var a = b.transform(type); 
console.log(type); 
b.transform(type); 
console.log(type);

1.麻烦去搜索一个三元运算符

2.就是闭包。

var type="";
        function Block()
        { 

            this.new=function()
            {
                type=type||"B1"; 
            } 

            this.transform=function(type)
            {
                switch(type)
                { 
                    case "B1":
                    //变纵向 
                    type = "B2";
                    break; 
                    case "B2":
                    //变横向 
                    type="B1"; 
                    break; 
                }
                function returnFun()
                {
                    return type;
                }

                return returnFun;

            } 
        } 

        var b=new Block();
        var c=b.new();
        var a=b.transform(type);
        alert(a());
        b.transform(type); 
        alert(type);

也可以这样理解吧:return "hello" + (who || '');

【热门文章】
【热门文章】