将引用复制到本地JavaScript方法是否安全? [英] Is it safe to copy a reference to a native JavaScript method?
问题描述
例如
var w = document.getElementById;
var b = w('header');
var c = w('footer');
var d = w('body');
编辑:分号是这些大论点中的另一个.我以为我会很有趣地编辑问题.
Semicolons are another one of those big arguments. I thought I would edit the question for fun.
编辑:对安德烈(Andrey)在他的答案中的评论进行了回复.
Responses to Andrey's comments found on his answer.
复制引用如何使其在JS编译器中更有效?"
响应:JS编译器将缩短和/或混淆代码.如果有40个对document.getElementById(..)
的调用,则调用getById(..)
会更紧凑,将其重命名为O(..)
之类.
"How does copying reference make it more effective with JS compilers?"
Response: JS compilers are to shorten and/or obfuscate code. If there were 40 calls to document.getElementById(..)
, it would be much more compact if they called getById(..)
which would be renamed to something like O(..)
.
此外,当您处理html元素事件时,通常会指定一个js方法,并且在该方法内部放置逻辑,而不是直接将其放置在html事件处理程序中-这不是必需的,而是一种很好的做法."
回复:我知道.但是我们有很多Web系统,它们很少完全遵循良好实践.
"Also, when you handle html element events, you usually specify a js method, and inside the method you put the logic, not directly in the html event handlers - that is not required but a good practice"
Response: I know. But we have many many web systems and they rarely follow good practice completely.
此外,直接使用内置方法会使代码更易读" 响应:考虑到这两个示例,我认为后者更具可读性
"Also, using built in methods directly makes the code way more readable" Response: Given these two examples, I think the latter is more readable
document.getElementById('total').value = document.getElementById('subtotal').value + document.getElementById('salestax').value - document.getElementById('discount').value
document.getElementById('yousaved').value = document.getElementById('discount').value / (document.getElementById('subtotal').value + document.getElementById('salestax').value)
或
var byId = document.getElementById
byId('total').value = byId('subtotal').value + byId('salestax').value - byId('discount').value
byId('yousaved').value = byId('discount').value / (byId('subtotal').value + byId('salestax').value)
推荐答案
您的意思是
var w = document.getElementById
?
此链接详细说明了为什么您不应该这样做: JavaScript函数别名似乎不起作用
Thsi link explains in detail why you shouldn't do that: JavaScript function aliasing doesn't seem to work
这篇关于将引用复制到本地JavaScript方法是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!