javascript 书写规范代码

书写规范的代码有利于后期的维护

可以先定义一个对象 如 var Main = {};

然后在Mian 对象里书写自己需要的方法和属性。

这样有利于减少不必要的全局变量;

下面是简单的例子:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js</title>
    <style type="text/css">
        *{padding: 0;margin: 0}
        body{overflow: hidden; 100%;height: 100%; }
        div{position: absolute;background: #000;color: #fff}
    </style>
</head>
<div id="en"></div>
<body>
<script type="text/javascript">
/*
    time : 2013-7-8;
    author : enen
*/
var Main = {
    cookie : {
        init :function(){
            console.log(this.set("feifei"))
        },
        set : function(name){
            return name;
        }
    },
    addNum : function (a,b){ //加法
        return a + b;
    }
};
Main.Fn  = function(){ //构造函数
    this.setCss(this.getId("en"),{"overflow":"hidden","height":"200px","width":"200px","background-color":"#ccc"})
}
Main.Fn.prototype  = { //通过prototype原型添加方法或属性
    getId :function(id){
        return document.getElementById(id)
    },
    setCss : function(ele,val){
        var str = "";
        for( var i in val){
            str += ";" + i+ ":" + val[i];
        }
        ele.style.cssText = str;
    }
}
console.log(Main.addNum(10,20)); //30
Main.cookie.init(); //feifei
new Main.Fn(); 
</script>

</body>
</html>
原文地址:https://www.cnblogs.com/enen/p/3177591.html