Home  >  Article  >  Web Front-end  >  How to detect functions in web development

How to detect functions in web development

php中世界最好的语言
php中世界最好的语言Original
2018-06-04 10:19:181371browse

This time I will show you how to detect functions in web development, and what are the precautions for detecting functions in web development. The following is a practical case, let's take a look.

Technically speaking, functions in JS are reference types. There is also Function

Constructor, and each function is an instance of it, such as:

function myFunc () {}// 不好的写法console.log(myFunc instanceof Function); // true// 好的写法console.log(typeof myFunc === 'function'); // true

However, This method cannot be used across frames because each frame has its own Function constructor. Fortunately, typeof

operator can also be used for functions, returning "function". The best way to detect functions is to use typeof because it can be used across frames.

There is a limitation in using typeof to detect functions. In IE8 and earlier versions of

IE browsers, functions using typeof to detect DOM nodes (such as document.getElementById()) all return " object" instead of "function". For example:

// IE 8及其更早版本的IEconsole.log(typeof document.getElementById); // "object"console.log(typeof document.createElement); // "object"console.log(typeof document.getElementByTagName); // "object"

The reason why this weird phenomenon occurs is because browsers have different implementations of DOM. In short, these early versions of IE did not implement the DOM as built-in JS methods, causing the built-in typeof operator to recognize these functions as objects. Because DOM is clearly defined, knowing that if an object member exists, it means it is a method. Developers often use the in operator to detect DOM methods, such as:

// 检测DOM方法if ("querySelectorAll" in document) {
  images = document.querySelectorAll("img");
}

This code checks whether querySelectorAll Defined in the document, if so, use this method. Although not the most ideal method, this is the safest approach if you want to detect the presence of DOM methods in IE8 and earlier browsers. In all other cases, the typeof operator is the best choice for detecting JS functions.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to detect original values ​​in web development

How to avoid null comparison in web development

The above is the detailed content of How to detect functions in web development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn