jquery.each() - " this“ vs valueOfElement [英] jquery.each() - "this" vs valueOfElement

查看:116
本文介绍了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 if valueOfElement is of primitive type

这篇关于jquery.each() - &quot; this“ vs valueOfElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆