JavaScript中的函数分类和讲解:普通函数(含对象的方法)、generator函数、async函数、async generator函数使用讲解

本文深入探讨ES6中引入的各种函数类型,包括普通函数、generator函数、async函数和async generator函数,详细介绍了它们的使用场景和调用方式,特别强调了在异步处理中的优势。

在ES6之前,JS中主要只有一种函数,ES6之后,加入了其他的一些函数,方便了很多其他场景的处理,尤其是异步场景的处理,用的合适,能大大的简化异步代码的处理。

一、普通函数:

这里所说的普通函数,包含普通函数、函数表达式定义的函数、对象中的方法,箭头函数等。普通函数是比较常见、常用的,这里描述一下涉及的调用方式:

// 1.1, 直接函数调用方式:
Person("迪丽热巴", 18, "直接函数调用");
// 1.2, 方法调用
obj.doSomeThing()

// 2, 构造函数方式
let person = new Person("杨超越", 18, "构造函数方式调用");

// 3, call和applay
Person.call(null, "刘亦菲", 19, "call调用");
Person.apply(null, ["汤唯", 20, "apply调用"]);

// 4, Reflect调用
Reflect.apply(Person, null, ["蔡依林", 20, "Reflect调用"]);

// 5,bind this之后再调用
let fn = Person.bind(null, "杨幂");
fn(18, "bind后调用")

注意:

1,箭头函数不能当构造函数。

2,对象的简写形式的方法不能用作构造函数,会报错。

const obj = {
    // 简写形式的方法,不能用作构造函数
    Cat(){
        this.type = "cat";
    },

    Dog: function(){
        this.name = "dog";
    }
}
new obj.Dog();
new obj.Cat();

// 以下是运行结果
new obj.Cat();
^

TypeError: obj.Cat is not a constructor
    at Object.<anonymous> (/~~~/object-test1.js:71:1)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11

二、generator函数

初接触使用这种函数的时候,感觉理解比较晦涩。看了N遍官方文档,各种练习之后,大致了解了它的使用和运转方式了。关于generator函数的使用场景,单独起一片文章介绍,这里先留个链接坑吧: https://blog.youkuaiyun.com/yangxinxiang84/article/details/106968137

关于该种类型的函数的详细介绍,参考 https://es6.ruanyifeng.com/#docs/generator

这里简要的描述和汇总下:

function testGenerator(){
    console.log(`testGenerator :: enter.`);
    let g = generator()
    for(let rst of g){
        console.log(`testGenerator :: rst = ${rst}`);
    }
}
testGenerator();


// generator函数
function* generator2(){
    let x = yield 5;
    console.log(`generator2 :: x = ${x}`);
    let y = yield 6;
    console.log(`generator2 :: y = ${y}`);
    let z = yield 7;
    console.log(`generator2 :: z = ${z}`);
    return x + y + z;
}
function testGenerator2(){
    console.log(`testGenerator2 :: enter.`);
    let g = generator2();
    let rst1 = g.next().value;
    let rst2 = g.next(100).value; // 将参数替换进入 generator函数 上一个 yield 的返回值 x的地方。
    let rst3 = g.next().value;
    let rst4 = g.next().value;
    console.log(`testGenerator2 :: end, rst1 = ${rst1}, rst2 = ${rst2}, rst3 = ${rst3}, rst4 = ${rst4}`);
}
 testGenerator2();

三、async 函数

async函数本质上是generator函数的语法糖,但是使用更清晰和简单。尤其在处理异步函数的时候,非常方便。

let {log} = require("../../util/logger");
function sleep(ms){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve(`sleep end :: ms = ${ms}`)
        },ms || 300);
    })
}
function mockFetch(url, ms){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            // 模拟resove和reject场景
            if(ms % 2 ===0){
                resolve(`mockFetch end :: url = ${url}, ms = ${ms}`);
            }else{
                reject(new Error("mockFetch :: error, not support!!"))
            }
        },ms || 600);
    })
}

async function testNormalAsync(){
    log(`testNormalAsync :: enter.`);
    // 同步的方式写异步,但是如果被reject,要写try catch捕获
    try{
        let rst1 = await sleep(1000); 
        log(`testNormalAsync :: after sleep, rst1 = ${rst1}`);

        let rst2 = await mockFetch("baidu.com", 201);
        log(`testNormalAsync :: after mockFetch, rst2 = ${rst2}`);
    }catch(e){
        log(`testNormalAsync :: error, ${e}.`);
    }
    log(`testNormalAsync :: end.`);
}
testNormalAsync();

// 以下是输出内容,注意看时间点
[12:12:56:182] testNormalAsync :: enter.
[12:12:57:208] testNormalAsync :: after sleep, rst1 = sleep end :: ms = 1000 //1秒后输出的
[12:12:57:414] testNormalAsync :: error, Error: mockFetch :: error, not support!!.// 又过了200毫秒输出的
[12:12:57:414] testNormalAsync :: end.

四、async generator函数

 

参看:https://blog.youkuaiyun.com/yangxinxiang84/article/details/106974312

<think>我们正在检查本地计算机是否安装Adobe Acrobat Reader DC。由于用户的问题是关于检测安装,我们可以通过几种方法来实现: 1. 检查注册表(Windows系统) 2. 检查应用程序目录(Windows、MacOS) 3. 使用命令行或脚本(如PowerShell、批处理、bash等) 考虑到用户可能使用不同的操作系统,我们将分别提供Windows和MacOS的检测方法。 注意:由于用户的问题中提到了Adobe Acrobat Reader DC,我们主要针对这个特定版本进行检测。 根据引用[5],我们知道Adobe Acrobat ReaderDC版本(最新版本)和XI版本(经典版本)。这里我们关注DC版本。 在Windows系统中,我们可以通过以下方式检测: - 检查注册表中Adobe Acrobat Reader DC安装信息。 - 检查程序安装目录(默认在C:\Program Files (x86)\Adobe\Acrobat Reader DC)。 在MacOS系统中,我们可以通过检查应用程序目录(/Applications/Adobe Acrobat Reader DC.app)。 另外,我们也可以尝试通过命令行调用Adobe Acrobat Reader DC的可执行文件,并检查返回的版本信息。 下面我们将分别提供Windows和MacOS下的检测方法。 一、Windows系统: 方法1:通过注册表 Adobe Acrobat Reader DC安装时会在注册表中创建键值,我们可以查看以下路径: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe 如果存在这个键,那么我们可以获取其默认值,该值就是可执行文件的路径。 方法2:通过PowerShell脚本 我们可以使用PowerShell命令来检查: Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion | Where-Object { $_.DisplayName -like "*Adobe Acrobat Reader DC*" } 方法3:通过文件系统 检查默认安装路径是否存在: C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe 二、MacOS系统: 通常,我们可以检查应用程序目录: /Applications/Adobe Acrobat Reader DC.app 或者使用终端命令: mdfind "kMDItemKind == 'Application'" | grep "Adobe Acrobat Reader DC" 此外,我们也可以编写一个跨平台的脚本(如Python)来检测,但需要根据操作系统执行不同的检测逻辑。 下面我们提供几种检测方法的示例代码: 1. Windows批处理脚本(check_adobe_reader.bat): ```batch @echo off setlocal set "regKey=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe" set "filePath=C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" reg query "%regKey%" 2>nul if %errorlevel% equ 0 ( echo Adobe Acrobat Reader DC is installed (found in registry). exit /b 0 ) if exist "%filePath%" ( echo Adobe Acrobat Reader DC is installed (found in file system). exit /b 0 ) echo Adobe Acrobat Reader DC is not installed. exit /b 1 ``` 2. Windows PowerShell脚本(check_adobe_reader.ps1): ```powershell # 检查注册表路径 $regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe" $installPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" if (Test-Path $regPath) { Write-Host "Adobe Acrobat Reader DC is installed (found in registry)." exit 0 } if (Test-Path $installPath) { Write-Host "Adobe Acrobat Reader DC is installed (found in file system)." exit 0 } Write-Host "Adobe Acrobat Reader DC is not installed." exit 1 ``` 3. MacOS/Linux Shell脚本(check_adobe_reader.sh): ```bash #!/bin/bash # 检查应用程序目录 if [ -d "/Applications/Adobe Acrobat Reader DC.app" ]; then echo "Adobe Acrobat Reader DC is installed." exit 0 fi # 尝试使用mdfind(仅MacOS) if command -v mdfind >/dev/null 2>&1; then result=$(mdfind "kMDItemKind == 'Application' && kMDItemDisplayName == 'Adobe Acrobat Reader DC'") if [ -n "$result" ]; then echo "Adobe Acrobat Reader DC is installed." exit 0 fi fi echo "Adobe Acrobat Reader DC is not installed." exit 1 ``` 4. Python脚本(跨平台): ```python import os import sys import platform def check_windows(): # 检查注册表 try: import winreg key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe" try: winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) return True except FileNotFoundError: pass except ImportError: pass # 检查文件路径 path = r"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" if os.path.exists(path): return True return False def check_macos(): path = "/Applications/Adobe Acrobat Reader DC.app" if os.path.exists(path): return True return False def main(): system = platform.system() installed = False if system == "Windows": installed = check_windows() elif system == "Darwin": installed = check_macos() else: # 对于Linux,Adobe Acrobat Reader DC不提供官方版本,但可能有其他方式安装,这里不处理 print("This script does not support Linux for Adobe Acrobat Reader DC.") sys.exit(1) if installed: print("Adobe Acrobat Reader DC is installed.") sys.exit(0) else: print("Adobe Acrobat Reader DC is not installed.") sys.exit(1) if __name__ == "__main__": main() ``` 注意:以上脚本都是示例,实际使用时可能需要根据具体环境调整(例如64位系统可能路径不同,或者用户自定义安装路径)。在Windows中,我们主要检查32位版本的路径,因为Adobe Acrobat Reader DC通常是32位的。在64位系统上,32位程序通常安装在“Program Files (x86)”目录下。 用户可以根据自己的操作系统选择合适的方法来检测。 另外,需要注意的是,如果用户安装的是其他版本(如Adobe Acrobat Pro DC),那么上述方法可能不适用。但问题明确要求检测Adobe Acrobat Reader DC。 最后,我们还可以通过尝试读取版本信息来进一步确认,但上述方法已经足够用于检测是否安装。 根据引用[5],用户可能下载了离线安装程序,因此我们也可以考虑检查其他可能的安装路径(如用户自定义路径),但通常上述默认路径已经覆盖了大多数情况。 如果用户需要更精确的检测(比如需要版本号),我们可以扩展脚本以获取版本信息。 以上方法供用户参考。</think>### 如何检测本地是否安装 Adobe Acrobat Reader DC 以下是几种可靠的检测方法,根据操作系统选择相应方案: --- #### **Windows 系统** 1. **通过注册表检测** ```powershell # PowerShell 命令 $regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe" if (Test-Path $regPath) { $installPath = (Get-ItemProperty $regPath).'(default)' Write-Host "已安装,路径: $installPath" } else { Write-Host "未安装 Adobe Acrobat Reader DC" } ``` 2. **检查安装目录** - 默认安装路径: ``` C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe ``` - 直接在文件资源管理器中检查该路径是否存在。 3. **命令行检测** ```cmd :: CMD 命令 where /R "C:\Program Files" AcroRd32.exe 2>nul if %errorlevel% equ 0 (echo 已安装) else (echo 未安装) ``` --- #### **macOS 系统** 1. **检查应用程序目录** ```bash # 终端命令 if [ -d "/Applications/Adobe Acrobat Reader DC.app" ]; then echo "已安装" else echo "未安装" fi ``` 2. **通过系统信息检测** ```bash # 列出所有 Adobe 应用 system_profiler SPApplicationsDataType | grep "Adobe Acrobat Reader DC" ``` --- #### **通用方法(跨平台)** 1. **尝试打开 PDF 文件** - 右键点击任意 PDF 文件 → "打开方式" → 检查是否有 **Adobe Acrobat Reader DC** 选项。 2. **通过控制面板/系统设置** - **Windows**:`控制面板 > 程序和功能` → 查找 Adobe Acrobat Reader DC - **macOS**:`系统设置 > 通用 > 存储空间 > 应用程序` → 查找 Adobe Acrobat Reader DC --- #### **编程检测(Python 示例)** ```python import winreg, os def check_adobe_reader(): try: # 检查注册表 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe") path = winreg.QueryValue(key, None) return True if os.path.exists(path) else False except FileNotFoundError: return False if check_adobe_reader(): print("Adobe Acrobat Reader DC安装") else: print("未检测到安装") ``` > **注意**: > - 以上方法优先检测 **Reader DC**(最新版),若需检测旧版(如 Reader XI),请替换路径中的 `DC` 为 `XI`[^5]。 > - 若通过编程检测,需以管理员权限运行脚本(Windows)。 --- ### 相关问题 1. **如何区分 Adobe Acrobat Reader DCAdobe Acrobat Pro DC?** > 两者功能差异主要体现在编辑能力上,Reader DC 仅支持查看/注释,Pro DC 支持PDF编辑/转换等高级功能[^4]。 2. **检测到已安装无法打开 PDF 文件,如何修复?** > 可尝试重设文件关联:`设置 > 应用 > 默认应用 > 按文件类型指定默认值 > 选择 .pdfAdobe Acrobat Reader DC`[^3]。 3. **Adobe Acrobat Reader DC 的离线安装包如何获取?** > 官方下载地址可通过分析在线安装页面获取,或直接使用提供的离线包链接[^5]。 4. **如何通过命令行静默安装 Adobe Acrobat Reader DC?** > 使用官方的 `AcroRdrDCxxxxx_xx_xx.exe /sAll` 命令进行无界面安装。 [^1]: Adobe Acrobat Reader DC 是处理 PDF 文件的可靠工具。 [^3]: Adobe Acrobat Reader DC 具备出色的文件兼容性。 [^4]: Adobe Acrobat Reader DC 提供基础阅读功能,Pro 版支持高级编辑。 [^5]: Adobe Acrobat Reader 的离线安装程序可通过分析在线地址获取。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值