JQuery this 和 $(this) 详解

this 

this 在面向对象语言中,指代调用上下文对象,在js中,也是一模一样的概念,所以不管这个this出现在什么地方,只要追踪到当前调用对象是什么,那么this是什么也就一目了然了。

先看一个简单示例

	(function(){
		console.log("Normal function being invoked by: "+ this);
	})();

输出: Normal function being invoked by: [object Window]

这是个普通匿名函数,当运行这段代码,谁是宿主对象呢,对, 全局变量window, 所以这里的this 就是 window


不过请注意如果是在严格模式下,这里的this是undefined, 下面代码可以验证

	(function(){
		'use strict';
		console.log("Normal function in strict: "+ this);
	})();

输出:Normal function in strict: undefined


上面的用法很傻,更常用的方式是在自定义的对象中用this指代自身,例如

	var o = { name: "Frank", 
	          sayName : function (){console.log(this.name)}}
	o.sayName();
输出:Frank

还有一个更实用的用法,是在函数中指代一个“未知的”调用上下文,也就是在定义函数时用到了this,但是这个函数被谁调用,我还不清楚,请在运行时自行绑定,这种用法在回调(callback)中很普遍,而实现这种函数和对象的动态关联,是通过函数的call( )和 apply( ) 方法实现的,看例子

	var o = { name: "Frank", age: 21}

	function sayAge(){
		console.log("My age is "+this.age)// 这个this 表示哪个对象调用我,我就是谁
	}

        sayAge.call(o); //当前上下文是 o, 所以age是21
	sayAge(); //当前上下文是 Window, Window没有age这个属性,所以是undefined

输出:

My age is 21

My age is undefined

OK, 理解了this,那么$(this) 就很简单了,在jQuery中,其作用就是将DOM对象wrap成一个jQuery对象,看个例子

<script src="jQuery.js" type="text/javascript"></script>
<script>
	$(function() {
		$('div').each(function(){
				this.style.color = "blue"; // this here is DOM element, because this function is fired by in the context of the current DOM element
				$(this).css( "color", "red" ); // use $(this) to wrap it to be jQuery object
			});
	});
</script>

<html>
 <body>
	<div> Sample 1 </div>
	<div> Sample 2 </div>
 </body>
</html>

此例中,each的参数是一个匿名的callback函数,其中的this就是前面介绍过的用法,指代运行时的调用对象,详细参见: http://api.jquery.com/each/

jQuery是怎么做到的呢? 看一下源码,很简单的

each: function( obj, callback, args ) {
		var value,
			i = 0,
			length = obj.length,
			isArray = isArraylike( obj );

		if ( args ) {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					// 就是这里了,通过call将执行callback函数的上下文设置为obj[i], 因为this指代函数运行时,invoke函数的对象(上下文),所以此时的this也就是obj[i]。而obj[i] 就是jQuery对象(数组)中的DOM对象,第二个参数是index,第三个参数基本不用,因为就是this
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) { //  如果你想终止loop,只要在回调函数中返回false就可以了
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}
		}

		return obj;
	},




版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/significantfrank/p/4875813.html