解决各种javascript类库冲突的办法
今天再次碰到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: }