今天再次碰到prototype類庫源碼和jQuery類庫源碼的衝突問題。
問題背景:
- 項目中已經大量引入了jQuery代碼,所以如果使用conflict的方法的話,勢必需要做大量的修改源碼工作。
- 要加入的原生代碼或者類庫代碼很少(片段)
解決思路:因為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: }