javascript 設計模式

類的設計

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
      <h1>Hello</h1>
  </body>
  <script>
    function Car(model){
        this.model=model;
        this.color="test";
        this.getInfo=function(){
            return this.model+" "+this.color;
        }
    }
    var myCar=new Car("mo");
    console.log(myCar.getInfo());
  </script>
</html>

構造器模式

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
      <h1>Hello</h1>
  </body>
  <script>
function Car(model,year,miles){
    this.model=model;
    this.year=year;
    this.miles=miles;
    this.toString=function(){
        return this.model+" has done"+this.miles+" miles";
    };
}
var civic=new Car("Honda Civic",2009,20000);
var mondeo=new Car("Ford Mondeo",2010,5000);

console.log(civic.toString());
console.log(mondeo.toString());
  </script>
</html>

Module模式

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Hello</h1>
</body>
<script>
var basketModule=(function(){
        //basket私有變量,無法從外界訪問
        var basket=[]

        function doSomethingPrivate(){
        alert("dosomethingprivate");
        }
        return {
        addItem: function(values){
        basket.push(values);
        }
        doSomething:doSomethingPrivate,
        getTotal:function(){
            var itemCount=this.getItemCount();
            return itemCount;
        }
}
})();
basketModule.addItem({item:"bread",price:0.5});
console.log(basketModule.getItemCount());

</script>
</html>

RevealingModule

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Hello</h1>
</body>
<script>
var myRevealingModule=function(){
    var private="Ben Cherry";
    var publicVar="Hey there!";
    function privateFunction(){
        console.log("Name:"+privateVar);
    }
    function publicSetName(strName){
        privateName=strName;
    }
    function publicGetName(){
        privateFunction();
    }
    return {
        setName: publicSetName,
        greeting:publicVar,
        getName:publicGetName
    };
}();
myRevealingModule.setName("Paul Kinlan");
</script>
</html>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章