---
title: "JavaScript及jQuery学习笔记(2)"
author: "QuarterLifeForJava"
date: "2014-11-17T16:51:49Z"
tags: []
categories: ["Web前端"]
slug: "javascript-jquery-2"
draft: false
lastmod: "2014-11-17T16:51:49Z"
id: 2157156
url: "https://quarterlifeforjava.iteye.com/blog/2157156"
---

<span style="color:red">最后更新日：2014年11月17日</span>
下面对整体外层的(function(window){})(window);进行改造。看下function(window){}中的window。jquery源码中写为：function(global,factory){}，我们打印出来可以看到global就是window对象,factory为undefined，因为我没有第二个参数（不明白我说的是什么意思？没关系，继续看下去就明白了。），如果你再给他加其它参数，往后打印出来的都是undefined。在jquery之前的版本写为：
(function(window,undefined){}(window))。

```js

<html>
<head>
<script>
function test(){
	$("#v").say();	
};

(function (global,factory){
	/*
	此处小弟没什么经验，不明白为什么要做这些判断，总之就是调用了function(window[,noglobal])方法。
	在下个代码片段中将举个例子具体说明下。
	*/
	if ( typeof module === "object" && typeof module.exports === "object" ) {
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}
	
})(typeof window!=="undefined"?window:this,function(window, noGlobal){
	//这里照着jquery的源码，我把原来在上面的搬到下面了，是一样的
	var test = (function(){

		var t = function(id){
			return new test.n.o(id);
		};

		t.n = t.prototype = {
			o   : function(id){
				return {
					say : function(){
						var change = document.getElementById(id.substring(1,id.length));
						change.innerHTML = "我是未来";
						change.style.width = "100%";
						change.style.height = "100%";
						change.style.fontSize = "100px";
						change.style.backgroundColor = "yellow";
					}
				};
			}
		
		};

		return t;
	}());

	window.$ = window.jquery = test;
});
</script>
<style type="text/css">
div{
	background-color:red;
	width:20%;
	height:20%;
}
</style>
</head>
<body>
	<div id="v" onclick="test()">请在此区域内点击我</div>
</body>
</html>

```


下面举个例子，说明下，为什么和之前的效果是一样的：

```js

<!DOCTYPE html>
<html>
<head>
<script>
(function (x,y){
	console.log(x);//输出window对象
	console.log(y);//输出 function(a,b){//TODO}
})(window,function(a,b){
	//TODO
});
</script>
</head>
<body>
</body>
</html>

```

<span style="color:red">
看到了吗？！x就对应着window，y就对应着闭包function(a,b){}。我要执行这个闭包不就只要y(a,b)就可以了吗！！！</span>再看下面的示例：

```js

<!DOCTYPE html>
<html>
<head>
<script>
(function (x,y){
	if(y!=undefined){
		y(3,7);
	}else{
		console.log("从这个示例来看，不会执行到我");
	}
})(window,function(a,b){
	console.log(a+b);
});
</script>
</head>
<body>
</body>
</html>

```

OK！！！至此，以后我们只要把重点全部放在function(window, noGlobal){...}里面就可以了，你自己可以看看jquery的源码万把行都是写在这里面的。