Home Web Front-end JS Tutorial JavaScript method to check whether a function is native code_javascript tips

JavaScript method to check whether a function is native code_javascript tips

May 16, 2016 pm 04:39 PM
function

我总是经常碰到需要检查某个function是否是原生代码的情况 —— 这是功能测试中一个很重要的内容: 函数是浏览器内置支持的,还是通过第三方类库模拟的。要检测这一点,最简单的办法当然是判断函数的 toString 方法返回的值啦。

JavaScript代码

判断函数是否是原生方法其实相当简单:

// 判断是否原生函数 
function isNative(fn) { 
// 示例: 
// alert.toString() 
// "function alert() { [native code] }" 
// '' + fn 利用了js的隐式类型转换. 
return (/\{\s*\[native code\]\s*\}/).test('' + fn); 
}
Copy after login

将函数转换为字符串表示的形式,并且执行正则匹配,这就是实现的原理。

升级版,Update!

;(function() { 

// 取得Object的toString方法,用于处理传入参数value的内部(internal) `[[Class]]` 
var toString = Object.prototype.toString; 

// 取得原始的Function的toString方法,用于处理functions的反编译代码 
var fnToString = Function.prototype.toString; 

// 用于检测 宿主对象构造器(host constructors), 
// (Safari > 4; 真的输出特定的数组,really typed array specific) 
var reHostCtor = /^\[object .+?Constructor\]$/; 

// 使用RegExp将常用的native方法编译为正则模板. 
// 使用 `Object#toString` 是因为一般他不会被污染 
var reNative = RegExp('^' + 
// 将 `Object#toString` 强转为字符串 
String(toString) 
// 对所有正则表达式相关的特殊字符进行转义 
.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&') 
// 为了保持模板的通用性,将 `toString` 替换为 `.*?` 
// 将`for ...`之类的字符替换,兼容Rhino等环境,因为他们会有额外的信息,如方法的参数数量. 
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') 
// 结束符 
+ '$' 
); 

function isNative(value) { 
// 判断 typeof 
var type = typeof value; 
return type == 'function' 
// 使用 `Function#toString`原生方法来调用, 
// 而不是 value 自己的 `toString` 方法, 
// 以免被伪造所欺骗. 
? reNative.test(fnToString.call(value)) 
// 如果type 不是'function', 
// 则需要检查宿主对象(host object)的情形, 
// 因为某些(浏览器)环境会将 typed arrays 之类的东西当作DOM方法 
// 此时可能不匹配标准的Native正则模式 
: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; 
}; 

// 可以将 isNative 赋值给你想要的变量/对象 
window.isNative = isNative; 
}());
Copy after login
isNative(isNative) //false 
isNative(alert) //true 
window.isNative(window.isNative) //false 
window.isNative(window.alert) //true 
window.isNative(String.toString) //true
Copy after login
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

The usage and function of Vue.use function The usage and function of Vue.use function Jul 24, 2023 pm 06:09 PM

Usage and Function of Vue.use Function Vue is a popular front-end framework that provides many useful features and functions. One of them is the Vue.use function, which allows us to use plugins in Vue applications. This article will introduce the usage and function of the Vue.use function and provide some code examples. The basic usage of the Vue.use function is very simple, just call it before Vue is instantiated, passing in the plugin you want to use as a parameter. Here is a simple example: //Introduce and use the plug-in

file_exists() function in PHP file_exists() function in PHP Sep 14, 2023 am 08:29 AM

The file_exists method checks whether a file or directory exists. It accepts as argument the path of the file or directory to be checked. Here's what it's used for - it's useful when you need to know if a file exists before processing it. This way, when creating a new file, you can use this function to know if the file already exists. Syntax file_exists($file_path) Parameters file_path - Set the path of the file or directory to be checked for existence. Required. Return file_exists() method returns. Returns TrueFalse if the file or directory exists, if the file or directory does not exist Example let us see a check for "candidate.txt" file and even if the file

What is the usage of js function What is the usage of js function Oct 07, 2023 am 11:25 AM

The usage of js function function is: 1. Declare function; 2. Call function; 3. Function parameters; 4. Function return value; 5. Anonymous function; 6. Function as parameter; 7. Function scope; 8. Recursive function.

How to use SOA functions in PHP How to use SOA functions in PHP May 18, 2023 pm 01:10 PM

With the development of the Internet, SOA (service-oriented architecture) has become an important technical architecture in today's enterprise-level systems. Services in the SOA architecture can be reused, reorganized and extended, while also simplifying the system development and maintenance process. As a widely used Web programming language, PHP also provides some function libraries for implementing SOA. Next, we will detail how to use SOA functions in PHP. 1. The basic concept of SOA. SOA is a distributed system development idea and architecture.

How to use Function interface in Java8 How to use Function interface in Java8 Apr 17, 2023 pm 09:04 PM

Introduction to the Function interface in Java 8 Java 8 provides a functional interface Function. This interface represents doing some operations on a parameter and then returning the value after the operation. This interface has an abstract method apply, which indicates the operation on the parameters. //Definition of JavaFunction interface @FunctionalInterfacepublicinterfaceFunction{Rapply(Tt);defaultFunctioncompose(Function

See all articles