JS高級---體會面向對象和麪向過程的編程思想

體會面向對象和麪向過程的編程思想

 

ChangeStyle是自定義的構造函數,再經過原型添加方法的函數。html

實例化對象,導入json參數,和建立cs,調用原型添加的方法函數編程

過渡,先熟悉記憶json

 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    div {
      width: 300px;
      height: 200px;
      background-color: red;
    }
  </style>
</head>

<body>
  <input type="button" value="顯示效果" id="btn" />
  <div id="dv"></div>
  <script src="common.js"></script>
  <script>


    function ChangeStyle(btnObj, dvObj, json) {
      this.btnObj = btnObj;
      this.dvObj = dvObj;
      this.json = json;
    }
    ChangeStyle.prototype.init = function () {
      //點擊按鈕,改變div多個樣式屬性值
      var that = this;
      this.btnObj.onclick = function () {
        for (var key in that.json) {
          that.dvObj.style[key] = that.json[key];
        }
      };
    };

    //實例化對象
    var json = { "width": "500px", "height": "300px", "backgroundColor": "blue" }
    var cs = new ChangeStyle(my$("btn"), my$("dv"), json);
    cs.init();//調用方法
  </script>
</body>

</html>
相關文章
相關標籤/搜索