解決各種javascript類庫衝突的辦法

來源:互聯網
上載者:User

今天再次碰到prototype類庫源碼和jQuery類庫源碼的衝突問題。

問題背景:

  1. 項目中已經大量引入了jQuery代碼,所以如果使用conflict的方法的話,勢必需要做大量的修改源碼工作。
  2. 要加入的原生代碼或者類庫代碼很少(片段)

解決思路:因為jQuery類庫是在全域對象的基礎上建立的,也就是在全域對象的原型鏈上建立的,所以我們只需要改變原生代碼或類庫程式碼片段的原型鏈(域),就可以了。

樣本:

    下面這是一段prototype類庫的代碼,如果和jQuery同時使用,會出現衝突現象。

   1:  <script>
   2:   
   3:  var isIE = (document.all) ? true : false;
   4:   
   5:  var $ = function (id) {
   6:      return "string" == typeof id ? document.getElementById(id) : id;
   7:  };
   8:   
   9:  var Class = {
  10:      create: function() {
  11:          return function() { this.initialize.apply(this, arguments); }
  12:      }
  13:  }
  14:   
  15:  var Extend = function(destination, source) {
  16:      for (var property in source) {
  17:          destination[property] = source[property];
  18:      }
  19:  }
  20:   
  21:  var Bind = function(object, fun) {
  22:      return function() {
  23:          return fun.apply(object, arguments);
  24:      }
  25:  }

    解決辦法:

   1:  var Sunny= new Object();//建立對象原生代碼的頂層對象Sunny,然後在該域下編寫類庫代碼
   2:  Sunny.isIE = (document.all) ? true : false;
   3:   
   4:  Sunny.$ = function (id) {
   5:      return "string" == typeof id ? document.getElementById(id) : id;
   6:  };
   7:   
   8:  Sunny.Class = {
   9:      create: function() {
  10:          return function() { this.initialize.apply(this, arguments); }
  11:      }
  12:  }
  13:   
  14:  Sunny.Extend = function(destination, source) {
  15:      for (var property in source) {
  16:          destination[property] = source[property];
  17:      }
  18:  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.