---
title: "Jquey代码安全(他山之石)"
author: "kylines"
date: "2012-08-23T18:48:59Z"
tags: []
categories: ["Web前端"]
slug: "jquey"
draft: false
lastmod: "2012-08-23T18:48:59Z"
id: 1660234
url: "https://kylines.iteye.com/blog/1660234"
---

在多人合作开发中一定要确保变量，对象，函数等命名不要冲突：
方法一：当别人使用了其他的js库，并该库使用了”$”变量，那么我们可以使用noConflict()方法：

```js
 var j = jQuery.noConflict();  
 // Now, instead of $, we use j.  
 j('#someDiv').hide();      
 // The line below will reference some other library's $ function.  
 $('someDiv').style.display = 'none';
```
 
方法二，把你的代码放在一个匿名函数里面，然后把jQuery作为参数传递给它，那么在这个函数体中的$是不会影响外面或者被外面影响的。

```js
(function($) {  
 // Within this function, $ will always refer to jQuery  
 })(jQuery);
```
 
方法三，通过ready方法传递$

```js
 jQuery(document).ready(function($) {  
 // $ refers to jQuery  
 });  
 // $ is either undefined, or refers to some other library's function. 
```