[js] 那些相见恨晚的 JavaScript 技巧

[1] js简洁的创建对象

 

function obj_test() {
                //方法1
                var car1 = new Object();
                car1.color = "red";
                car1.wheels = "4";
                car1.hupcaps = "spinning"
                car1.age = 4;
                //方法2
                var car2 = {color:'red', wheels:'4', hubcaps:'spinning', age:'4'};
                var tmp = '';
                for(value in car2) {
                    tmp += value +',';
                }
                alert(tmp);
}

 

[2] js简洁的创建数组

 

function arr_test() {
                //方法1
                var arr1 = new Array('a', 'b', 'c');
                
                //方法二
                var arr2 = ['a', 'b', 'c'];
                var tmp = '';
                for(var i=0; i<arr1.length; i++) {
                    tmp += arr2[i] + ',';
                }
                alert(tmp);
            }

 

[3]js三元符号

 

function other_test() {
                var sign = 1;
                var value = sign ? 1 : 0;
                alert(value);
            }

 

[4]js使用json格式缓存复杂的数据

 

function json_test() {
                //json解决了缓存复杂数据的困境
                var band = {
                    "name":"liu86th",
                    "members":[
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"}
                    ],
                    "year":"2000"
                };
                var value = eval(band);
                for(var j=0; j<value.members.length; j++) {
                    alert(value.members[j].name);
                }
            }

 

[5] js内置函数

 

function json_test() {
                //json解决了缓存复杂数据的困境
                var band = {
                    "name":"liu86th",
                    "members":[
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"},
                        {"name":"liu", "role":"hero"}
                    ],
                    "year":"2000"
                };
                var value = eval(band);
                for(var j=0; j<value.members.length; j++) {
                    alert(value.members[j].name);
                }
            }

function string_test() {
                //方法一
                function addclass(elm, newclass) {
                    var c = elm.className;
                    elm.className = (c == '') ? newclass : c+' '+newclass;
                }
                
                //方法二
                function addclass2(elm , newclass) {
                    var classes = elm.className.split(' ');
                    classes.push(newclass);
                    elm.className = classes.join(' ');
                }
            }

 

[6] js事件

 

function event_test() {
                //<h2> greate web resources </h2>
                //<ul id="resources">
                //<li> <a href="http://www.sina.com"> a </li>
                //<li> <a href="http://www.sina.com"> b </li>
                //<li> <a href="http://www.sina.com"> c </li>
                //<li> <a href="http://www.sina.com"> d </li>
                //<li> <a href="http://www.sina.com"> e </li>
                //</ul>
                //方法一
                (function(){
                    var resources = document.getElementById('resources');
                    var links = resources.getElementsByTagName('a');
                    var length = links.length;
                    for(var i=0; i<length; i++) {
                        links[i].addEventListener('click', handler, false);
                    }
                    function handler(e) {
                        var x = e.target;
                        alert(x);
                        e.preventDefault();
                    }
                })();

                //方法二
                (function(){
                    var resources = document.getElementById('resources');
                    resources.addEventListener('click', handler, false);
                    function handler(e) {
                        var x = e.target;
                        if(x.nodeName.toLowerCase() === 'a') {
                            alert('Event delegation ' + x);
                            x.preventDefault();
                        }
                    }
                })();
            }

 

[7] js单例模式

 

//1:方法1
            var name = 'liu';
            var age = 26;
            var status = 1;
            function create() {
                //....
            }
            function getMemberDetails() {
                //....
            }
            
            //2:为了避免上面成为全局变量,你可以使用匿名函数:
            var myApplication = function() {
                var name = 'liu';
                var age = 26;
                var status = 1;
                function create() {
                    //....
                }
                function getMemberDetails() {
                    //....
                }
            };
            
            //3:如果这个函数不被调用,你更可以这样
            (function(){
                var name = 'liu';
                var age = 26;
                var status = 1;
                function create() {
                    //....
                }
                function getMemberDetails() {
                    //....
                }
            })();
            
            //4:如果需要访问其中的函数或对象,可以这样
            var myApplication = function() {
                var name = 'liu';
                var age = 26;
                var status = 1;
                return {
                    function create() {
                    //....
                    }
                    function getMemberDetails() {
                    //....
                    }
               }
            }();
            //myApplication.create()
            //myApplication.getMemberDetails();
            //这就是所谓 Module模式或单例模式(Singleton),该模式为 Douglas Crockford 所推崇,并被大量应用在 Yahoo User Interface Library YUI。
            
            //假如你想在别的地方调用里面的方法,又不想在调用前使用 myApplication 这个对象名,可以在匿名函数中返回这些方法,甚至用简称返回:
            var myApplication = function() {
                var name = 'liu';
                var age = 6;
                var status = 1;
                function create() {
                    alert(name);
                }
                function getMemberDetails() {
                    alert(age);
                }
                return {
                    ch:create,
                    g:getMemberDetails
                }
            }();
            //调用: myApplication:c() myApplication:g()
            
            myApplication.ch();
[8] 定时执行传递参数
setInterval(test(a,b),1000,a,b)这样的形式(手册上面都是这样写的),浏览器会报参数无效的错误。可以新建一个临时函数做表达式传给setTimeout和setInterval函数。
例子:
var myTimeout=setTimeout(function(){f(x,y);}, n); 
var myInterval=window.setInterval(function(){startCounter(a);},100); 
 

你可能感兴趣的:(JavaScript)