简体   繁体   English

Javascript:确保参数产生有效的HTML元素(类型检查)

[英]Javascript: Ensuring an argument yields a valid HTML element (type-checking)

I have been going through some of my old code, and a lot of it employed snippets I grabbed online. 我一直在阅读一些旧代码,其中许多使用了我在网上抓取的代码片段。 I ran across a couple such borrowed functions that require an element as an argument, but this element can be passed in either as the element itself, or as a string to be used in .getElementById() . 我遇到了几个这样的借用函数,它们需要一个元素作为参数,但是可以将该元素作为元素本身或在.getElementById()使用的字符串来传递。 Which of the below two is better, and why? 以下两个中哪一个更好,为什么? Or is there an even better version? 还是有更好的版本? (Better = readable, standard, safe) (更好=可读,标准,安全)

Version 1 版本1

function doSomethingWithElem( elem /*, param2, ... */ ) {
    elem = (typeof elem === 'string' || elem instanceof String)
         ?  document.getElementById( elem )
         :  elem;

    // more stuff...
}

Version 2 版本2

function doSomething2( elem /*, param2, ... */ ) {
    elem = document.getElementById( elem ) || elem;

    // more stuff...
}

The primary difference being that one checks for an instance of string before calling gEBI, whereas the other relies on gEBI returning undefined . 主要区别在于,一个在调用gEBI之前检查字符串的实例,而另一个依赖gEBI返回undefined Neither of them checks to make sure elem is indeed an HTMLElement . 他们都不检查确保elem确实是HTMLElement

Assuming a well-defined API (the user knows he should pass in a string or HTML element), how important is type-checking? 假设有一个定义明确的API(用户知道他应该传递一个字符串或HTML元素),类型检查有多重要? Is type-checking primarily needed to help users of your scripts to debug their own code? 是否主要需要类型检查来帮助脚本用户调试自己的代码? Are there subtle pitfalls of either of these, such as possible return values of gEBI that could mess up version 2? 这两种方法中是否都存在细微的陷阱,例如gEBI的可能的返回值可能会使版本2混乱?

I'd go with version 1 as it's more readable. 我会选择版本1,因为它更具可读性。 You see that it handles 2 cases and what more clearly, one of them being a string the other an element directly. 您会看到它处理2种情况,更清楚的是,其中一种是字符串,另一种是直接元素。 I have never seen a check against instanceof String though, as to my experience in 99% people declare string primitives. 不过,我从未见过对instanceof String的检查,因为我在99%的人中都声明过字符串原语。 I tested gEBI a bit and it seems quite robust, it'll just return null for anything invalid (arrays, functions, objects, ...). 我对gEBI进行了一些测试,它看起来很健壮,对于任何无效的东西(数组,函数,对象等),它只会返回null

As to check whether elem actually is an HTML element see this: JavaScript isDOM -- How do you check if a JavaScript Object is a DOM Object? 要检查elem是否实际上是HTML元素,请参见: JavaScript isDOM-如何检查JavaScript对象是否为DOM对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM