jquery.each() - " this“ vs valueOfElement [英] jquery.each() - "this" vs valueOfElement
问题描述
在 jQuery.each()循环中,我一直认为此
相当于 valueOfElement
。有人可以解释一下这个区别吗?
In a jQuery.each() loop, I always thought that this
was equivalent to valueOfElement
. Could someone explain the difference?
示例:
$.each(object, function(i, val){
$('body').append('<b>valueOfElement:</b> ' + typeof val + ' - ' +
'<b>this: </b>' + typeof this + '<br/>');
});
结果:
valueOfElement: string - this: object
valueOfElement: boolean - this: object
valueOfElement: object - this: object
推荐答案
答案在您链接到的文档中:
The answer is in the documentation you linked to :
值可以也可以通过this关键字访问,但
Javascript将始终将此值包装为Object,即使它是
a简单字符串或数字值。
The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.
当以此
进行访问时,所有值都嵌入到对象中。
All values are embedded in objects when accessed as this
.
真正的原因可以在 jQuery source 这一行中找到:
The real reason can be found in this line of jQuery source :
callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
您可以比较它
(function(){console.log(this)}).call(1);
构建一个 Number
,因为你可以不要在非对象的东西上调用函数。
which builds a Number
, because you can't call a function on something that isn't an object.
来自呼叫功能上的MDN :
thisArg :
请注意,这可能不是方法看到的实际值:如果
方法是非函数严格模式代码,null和undefined将
替换为全局对象,原始值将是
盒装。
Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
我在使用这个
而不是 valueOfElement
时会看到的唯一优点是:
The only advantages I would see in using this
instead of valueOfElement
are :
- 简单:你不必记住给回调的参数顺序
- 使用函数的能力直接在
此
上,即使valueOfElement
是原始类型
- simplicity : you don't have to keep in mind the order of arguments given to the callback
- ability to use a function directly on
this
even ifvalueOfElement
is of primitive type
这篇关于jquery.each() - " this“ vs valueOfElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!