<分区>
Possible Duplicate:
What is the cost of '$(this)'?
就性能和可读性而言,命名变量而不是使用 $(this)
是好的做法吗?
一个例子是
$(".element").click(function() {
var elem = $(this);
//Examples
elem.addClass("example");
console.log( elem.attr("id") );
}):
标签 javascript jquery
<分区>
Possible Duplicate:
What is the cost of '$(this)'?
就性能和可读性而言,命名变量而不是使用 $(this)
是好的做法吗?
一个例子是
$(".element").click(function() {
var elem = $(this);
//Examples
elem.addClass("example");
console.log( elem.attr("id") );
}):
最佳答案
是的。由于 $(this)
本质上是一个非常昂贵的函数调用,它会触发 Dom-Search,因此您每次调用 $(this)
时都会重复它,而 var elem = $ (this);
函数调用一次并将结果存储在变量中。
实际上,将选择器传递给函数比传递像 this
这样的 DOM 元素要昂贵得多。所以缓存 this
只会产生非常小的影响,而缓存像 $("#foo[name|='bar']")
这样的东西真的很重要。
我更喜欢在变量名前加上 $
,这样很明显您在这里有一个 jQery 对象。
$this = $(this);
现在 $this
在具有性能优势的同时,从可读性的 Angular 来看没有明显的缺点。它也可以通过压缩器缩小为单个字母变量,而 $(this)
不能。
关于javascript - 使用变量而不是 $(this) 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556893/
相关文章:
javascript - 在 React 中使用 async/await 不正确地更新状态
javascript - 在 Jquerymobile 中获取 slider 的值?
javascript - 如何在自动完成 jquery 中过滤 JSON 数组并在 JavaScript 中显示动态值?
javascript - 如何使用 Protractor 测试比较具有 getSize() 函数的元素的宽度和高度?
javascript - 如何避免在 React 中使用 setProps?
javascript - 为什么 SVG 渲染比 PNG 渲染差这么多?
jquery - 仅当滚动位置在 2 点之间时才使用 jQuery 显示 div