首页 > 解决方案 > 未捕获的 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);
      });

标签: javascriptjqueryuncaught-exceptionjquery-rotatenodejs-8.11

解决方案


您应该使用箭头函数或将函数绑定到“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

祝你好运!


推荐阅读