On the pointing problem of this

read a lot of blogs on the direction of this is very confused, today read the blog is also some do not quite understand, I hope you can give us some advice.
paste the code:

var point = {
    x : 2,
    y : 2,
    moveTo : function(x, y) {
      var moveX = function(x) {
        this.x = x;
      };

      var moveY = function(y) {
        this.y = y;
      };
      moveX(x);
      moveY(y);
 }
  };
  point.moveTo(1, 1);
  console.log(point.x); //==>2
  console.log(point.y) //==>2
  console.log(x); //==>1
  console.log(y); //==>1

my understanding is that, first of all, this is an object method call. This points to point when moveTo is called, but when moveX (x); moveY (y) is executed. The this in it should have changed, and it doesn"t point to point, so point.x is still equal to 2. And there are two more global variables xpeny. What I want to ask is, has this changed? Why there are two global variables.

Mar.16,2021
If

has no definite calling object, it points to global by default, which means window in the browser, so this.x = x is equivalent to window.x = x , which is equivalent to creating a global variable.


moveTo, moveX, and moveY do not define this points, so the this direction of their runtime depends on the this direction of the running environment when the function is called. As far as the code you write, the this points to window, when you call, so their this at run time is window, so there are two global variables
moveTo. The this never points to point


.

moveX,moveY is declared from moveTo, can only be used in moveTo, there is no calling object, can only point to window
, and moveTo's this is called through Point, so this points to Point.

if you want to modify the result of Point X, Y, you can only return the value of moveX,moveY to this using return

var point = {
    x : 2,
    y : 2,
moveTo : function(x, y) {
  var moveX = function(x) {
    return x;
  };

  var moveY = function(y) {
    return y;
  };
thix.x=moveX(x);
this.y=moveY(y);
  };
  point.moveTo(1, 1);
  

or modify the var in moveTo to this, when moveTo is called, declare moveX, moveY in the Point object.
when you use moveX, moveY in moveTo at this time, you need to change it to this.moveX, this.MoveY.

var point = {
    x : 2,
    y : 2,
    moveTo : function(x, y) {
      this.moveX = function(x) {
        this.x=x;
      };

      this.moveY = function(y) {
        this.y=y;
      };
      this.moveX(x);
      this.moveY(y);
 }
  };
  point.moveTo(1, 1);
Menu