javascript - 在同一个构造函数(JS)中调用方法时“不是函数”
问题描述
我想在同一个类的方法中调用一个方法。
function Dialog() {
this.close = function() {
//code
};
this.dialog = document.createElement("div");
this.dialog.onclick = function() {
this.close();
}
document.body.appendChild(this.dialog);
}
var test = new Dialog();
我搜索了答案,但没有任何帮助:TypeError: this.close is not a function
当我单击 div 时,我仍然进入浏览器的控制台。
解决方案
当你使用function() { ... }
它时,它会改变this
函数内部的内容。您需要将该函数绑定到this
或使用箭头函数() => { ... }
。
使用绑定:
var handleClick = function() {
this.close();
};
this.dialog.onclick = handleClick.bind(this)
使用箭头函数:
this.dialog.onclick = () => {
this.close();
}
推荐阅读
- ios - 即使手机设置为静音,Swift AudioServicesPlaySystem也会播放声音?
- sorting - 如何使用 .sort 命令修复 Google 表格自动排序器中的 TypeError?
- matlab - 我如何获得函数的近似值?
- java - 如何测量 webflux WebClient 方法的执行时间?
- javascript - TypeError [ERR_INVALID_ARG_TYPE]:“url”参数必须是字符串类型。收到未定义
- postgresql - 如何在 Postgres 中获取有效列数据类型的列表
- powershell - Powershell 输出中的条件
- sql - 错误 #2014 调用存储过程时命令不同步
- node.js - 反应和表达:从公共文件夹中获取图像
- jenkins - X 射线扫描未在 Jenkins 管道中完成