嵌套函数上的“this”关键字应用

如何解决嵌套函数上的“this”关键字应用

我有这个代码:

<!DOCTYPE html>

<html>
    <head>
        <title>Drag-Drop tests</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <script>
            var body = document.body;
            
            var cursor = document.createElement("div");
            cursor.innerText = "Contenus des fichiers :\n";
            
            cursor.ondragover = e => e.preventDefault();
            cursor.ondrop = function(e) {
                e.preventDefault();
                
                if (e.dataTransfer.items) {
                    for (var i = 0; i < e.dataTransfer.items.length; i++) {
                        if (e.dataTransfer.items[i].kind === "file") {
                            var file = e.dataTransfer.items[i].getAsFile();
                            
                            file.cursor = document.createElement("p");
                            body.appendChild(file.cursor);
                            
                            file.cursor.innerText = file.name + " contient :";
                            
                            file.text().then(function(value) {
                                file.cursor.innerText += " " + value;
                            });
                        }
                    }
                }
                else {
                    for(var i = 0; i < e.dataTransfer.files.length; i++) {
                        var file = e.dataTransfer.files[i];
                            
                        file.cursor = document.createElement("p");
                        body.appendChild(file.cursor);
                        
                        file.cursor.innerText = file.name + " contient :";
                        
                        file.text().then(function(value) {
                            file.cursor.innerText += " " + value;
                        });
                    }
                }
            };
            
            body.appendChild(cursor);
        </script>
    </body>
</html>

按原样,如果我在 div 元素上放置两个文件,我会得到以下输出:

Contenus des fichiers :

File1.txt contient :

File2.txt contient : Content of file 1 Content of file 2

在 file.text().then 函数中,“file”指的是最后一个声明的文件引用。

如果我更换 file.cursor.innerText += by this.cursor.innerText += 我得到这个输出:

Contenus des fichiers :
Content of file 1 Content of file 2

File1.txt contient :

File2.txt contient :

在file.text().then函数中,“this”指的是第一个调用者,即div本身。

有什么办法可以做到这一点:

Contenus des fichiers :

File1.txt contient : Content of file 1

File2.txt contient : Content of file 2

保持匿名嵌套函数作为调用者的参数。

我知道 then 在我定义它的回调时不会发生。 我想知道我是否可以附上一些数据 到一个对象并在回调执行时检索它。

提前谢谢。

解决方法

在 file.text().then 函数中,“file”指的是最后一个声明的文件引用。

你来自 C 背景。在 JS 中,var 是函数作用域并获得 hoisted。最好将较新的关键字 letconst 用于块作用域变量。

What's the difference between using “let” and “var”?

在file.text().then函数中,“this”指的是第一个调用者,即div本身。

JS 中的

this 是臭名昭著的;特别是对于那些已经对其应该如何表现抱有期望的人。在 JS 中,this 是上下文相关的,取决于如何调用函数/方法。

How does the “this” keyword work?

旁注:我看到你写了两次代码,看看Iterators and Generators。我使用它们将 dataTransfer 中可用的任何内容“标准化”为一系列 File

var body = document.body;

var cursor = document.createElement("div");
cursor.innerText = "Contenus des fichiers :\n";

// https://mdn.io/Generator
function* getFiles(dataTransfer) {
  if (dataTransfer.items) {
    // https://mdn.io/for...of
    for (let item of dataTransfer.items) {
      if (item.kind === "file") {
        // https://mdn.io/yield
        yield item.getAsFile();
      }
    }
  } else {
    // https://mdn.io/yield*
    yield* dataTransfer.files;
  }
}

cursor.ondragover = e => e.preventDefault();
cursor.ondrop = function(e) {
  e.preventDefault();

  for (const file of getFiles(e.dataTransfer)) {
    const fileCursor = document.createElement("p");
    fileCursor.innerText = file.name + " contient :";

    body.appendChild(fileCursor);

    file.text().then(text => fileCursor.append(text));
  }
};

body.appendChild(cursor);

编辑:

我什至没有看到任何 let、const、function*、yeld 和 yeld*。

在 2020/21 年,这基本上是课程方面的失败。 constlet 已经在 ES2015 (Javascript 版本) 中引入,并且多年来基本上在每个浏览器中都实现了。

您如何命名这种在“fonction”或“yeld”关键字后添加星号的微妙之处?

一般主题是Iterators and Generators。我在上面的代码片段中为不同的关键字添加了一些特定的网址。

,

.text() 是异步的。所有 .then() 发生在整个 for 循环结束之后。非常经典的异步循环操作问题。您只需要 await 而不是使用(老派).then() 语法。

cursor.ondrop = async function(e) {
     // ...
     for(...) {
         const value = await file.text();
         file.cursor.innerText += " " + value;
     }
}
,

JSFiddle: https://jsfiddle.net/7q9Lphjf/1/

您得到这个结果是因为 += " " + value 发生在 Promise 执行之后。换句话说,在您的示例代码中,发生了以下步骤:

  1. 将“文件 1 内容”添加到 div。
  2. 开始读取文件 1
  3. 将“File2 内容”添加到 div。
  4. 开始阅读文件 2

[...] 几分钟后

  1. file1读取完成,promise解决,file1的内容被追加到div中
  2. file2读取完成,所以promise解决,file2的内容被追加到div中

在这种特殊情况下,它还与在 for 循环中更改的 file 变量的作用域有关,因此在 promise1 被解析时,file 已经引用了第二段,所以 file.cursor.innerText 指的是第二段的内容。

代替:

file.cursor = document.createElement("p");
body.appendChild(file.cursor);
file.cursor.innerText = file.name + " contient :";
                            
file.text().then(function(value) {
  file.cursor.innerText += " " + value;
});

使用:

file.text().then(function(value) {
  file.cursor = document.createElement("p");
  body.appendChild(file.cursor);
  file.cursor.innerText = file.name + " contient :";
  file.cursor.innerText += " " + value;
});

然而,此解决方案不保证任何特定顺序。每当为文件解析承诺时(文件读取完成),只有该文件的内容才会添加到 div 中。

如果您绝对需要附加内容的特定顺序,有许多可能的解决方案也可以实现这一点,例如承诺链。

但是我不确定这是否是一个要求,所以我不会让这个答案比现在更长:)

,

好的,

另一个答案指出“var”作用域是函数而不是块。

在任何地方用“let”替换“var”会使file.text()中的关键字“this”。然后回调不会因为执行流程而指向任何东西。

无论如何,“让”使每个迭代的“文件”独立。

因此我有这个代码工作:

<!DOCTYPE html>

<html>
    <head>
        <title>Drag-Drop tests</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <script>
            let body = document.body;
            
            let cursor = document.createElement("div");
            cursor.innerText = "Contenus des fichiers :\n";
            
            cursor.ondragover = e => e.preventDefault();
            cursor.ondrop = e => {
                e.preventDefault();
                
                let fileLoad = file => {
                    file.cursor = document.createElement("p");
                    body.appendChild(file.cursor);
                    
                    file.cursor.innerText = file.name + " contient :";
                    file.text().then(value => file.cursor.innerText += " " + value);
                }
                
                if(e.dataTransfer.items)
                    for(let item of e.dataTransfer.items)
                        if(item.kind === "file") fileLoad(item.getAsFile());
                else
                    for(let file of e.dataTransfer.files)
                        fileLoad(file);
            };
            
            body.appendChild(cursor);
        </script>
    </body>
</html>

最后,我并不真正关心代码优化(对于行代码的数量)。

我会用一些 C 代码生成它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res