DOM方法的简短变量 [英] Short variable for DOM methods
问题描述
不能对 document.createElement
, document.createTextNode
,<等方法设置快捷方式 code> [element] .setSelectionRange etc?
var c = document.createElement;
var div = c('div');
div.innerHTML = 'blah';
document.body.appendChild(div);
执行上述代码时, Firebug控制台会返回错误:
未捕获的异常:[异常......无法转换JavaScript参数nsresult:0x80570009(NS_ERROR_XPC_BAD_CONVERT_JS)location:JS frame :: < a href =http://fiddle.jshell.net/_display/ =nofollow> http://fiddle.jshell.net/_display/ ::: line 20data:no]
uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://fiddle.jshell.net/_display/ :: :: line 20" data: no]
这种情况发生在这里提供的jsfiddle 并且在没有错误的情况下在jsfiddle之外完成时默默地失败。
This happens on jsfiddle as provided here and silently fails when done outside of jsfiddle with no errors.
以下代码工作正常,因此它仅限于DOM操作方法?
The below code works fine, so is it just limited to DOM manipulation methods?
function long_function_name(prop)
{
alert(prop);
}
var c = long_function_name;
c('blah');
这有压缩的实际示例清酒:
而不是:
if (element.setSelectionRange)
{
element.setSelectionRange(pos, pos);
}
压缩到:
var s = element.setSelectionRange || 0;
if (s) s(pos, pos);
推荐答案
有两个明显的问题:
- 调用别名函数将无法提供正确的
此
值(它将是全局对象而非比document
),DOM方法可能依赖或不依赖; - JavaScript中的DOM节点是主机对象,它们不受本机JavaScript对象的正常规则约束,并且基本上可以执行他们喜欢的操作。例如,无法保证宿主对象的方法是常规的
Function
对象,因此可能没有call()
或apply()
您可以用来提供正确此
值的方法。
- Calling your aliased functions will not be providing the correct
this
value (it will be the global object rather thandocument
), which the DOM method may or may not depend upon; - DOM nodes in JavaScript are host objects, which are not subject to the normal rules of native JavaScript objects and can essentially do what they like. For example, there is no guarantee that a method of a host object is a regular
Function
object and may not therefore have thecall()
orapply()
methods that you could otherwise use to provide the correctthis
value.
在这种情况下,你最好改为编写包装函数,例如
This being the case, you're better off writing a wrapper function instead, such as
function c(tagName) {
return document.createElement(tagName);
}
这篇关于DOM方法的简短变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!