javascript - 未捕获的 TypeError:this.rotate 不是函数
问题描述
我创建了一个用于旋转 div 元素的函数。这可以作为 HTML 中的独立代码正常工作,当我尝试将其合并到我的项目中时,旋转函数会引发错误,因为“未捕获的 TypeError:this.rotate is not a function”。我的项目基于节点版本 8,我已将 HTML 转换为 Pug 并使用它。我在下面给出了我的代码:
var rotation = 0;
$.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
$('.box').click(function() {
rotation += 5;
this.rotate(rotation);
});
解决方案
您应该使用箭头函数或将函数绑定到“this”
var rotation = 0;
$.fn.rotate =(degrees) => {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
$('.box').click(() => {
rotation += 5;
this.rotate(rotation);
});
与常规函数相比,箭头函数的处理也不同。
简而言之,箭头函数没有 this 的绑定。
在常规函数中,this 关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何东西。
对于箭头函数,this 关键字始终表示定义箭头函数的对象。
https://www.w3schools.com/js/js_arrow_function.asp
祝你好运!
推荐阅读
- linear-algebra - 由转换为 xy 坐标的圆锥底形成的平面
- flutter - 在颤动中创建了不必要的对象并占用了内存
- python - 在托管的 http.server.BaseHTTPRequestHandler 中获取访问者的 ipv4 地址
- python - 无法为 python slack api 导入名称“Webclient”
- ios - 在 iOS 上一次可以播放多少个声音 - AVAudioPlayer vs. AVAudioEngine & AVAudioPlayerNode
- c# - 在 C# 中读取具有各种变量类型的行
- arrays - 我的 firebase 数据正在获取但没有附加到我的数组中?
- intellij-idea - IntelliJ IDEA - 使用热键删除文件末尾的空行
- javascript - 下载或导出 Chart.js 数据到 CSV
- delphi - 使用 GifImage 从 gif 中提取帧