1

I have created a function for rotating a div element. This works fine as a standalone code in HTML and when I tried to incorporate in my project the rotate function throws an error as "Uncaught TypeError: this.rotate is not a function". My project is based on node version 8 and I have converted HTML to Pug and used it. I have given my code below:

      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);
      });

1 Answers1

0

You should use arrow functions or bind the function to '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);
  });

The handling of this is also different in arrow functions compared to regular functions.

In short, with arrow functions there are no binding of this.

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the this keyword always represents the object that defined the arrow function.

https://www.w3schools.com/js/js_arrow_function.asp

Good luck!

Erez Shlomo
  • 2,124
  • 2
  • 14
  • 27