personal notes of this

Use the constructor to create a function, and then use the function in the new way, which is equivalent to creating an object

function User(name) {
    
    
 this.name = name;
 this.show = function () {
    
    
  console.log(this.name);
  function render() {
    
    
   // window对象
   console.log(this);
  }
  render();
 };
}
let xiaoming = new User('小明');
console.log(xiaoming.show()); //小明

① In an object, when a function belongs to a certain attribute of the object, then the function is called: method/class method

② If the function in the object does not belong to a certain attribute, then this function is just a function

③This of the method/class method points to the current object

④ This of the function points to the window object

⑤Define a global variable, which is stored in the window object

// name = "window's name";
let obj = {
    
    
 site: 'https',
 // show 是一个方法
 show: function () {
    
    
  // this 是这个obj对象
  console.log(this);
  // render()是一个函数
  function render() {
    
    
   // this 是window对象
   console.log(this);
   console.log(this.name);
  }
  render();
 },
};
console.log(obj.show());

Extension of this 1

let obj_cart = {
    
    
 site: 'https://shopCart.com',
 front: 'world-',
 lists: ['js', 'html', 'css'],
 // 使用show()方法给lists的每一项都加上 “world-”/front 的前缀
 show: function () {
    
    
  // console.log(this);
  // 因为lists是数组,可以用map()方法

  // 用一个常量来存储this,这样map()中的回调函数需要用到对象内容的地方,用这个常量来代替就可以了
  // 也就避免了this指向window
  const self = this;

  this.lists.map(function (value) {
    
    
   // 此时是可以正确读到obj_cart对象中的lists的每一个值
   console.log(value); // js html css
   // 这时候需要注意,在show()中,因为show是属于obj_cart对象的一个方法,所以show内部的this指向的是该对象
   // 但是在map()方法中,它的回调函数不是属于show的,它不是一个类方法,所以map()中的this,是指向window的
   // console.log(this.front + value); //undefinedjs undefinedhtml undefinedcss

   // 常用的方法是:在show中的this指向本对象的时候,就用一个 常量/变量 来存储它,这样this就不会变了

   console.log(self.front + value); // world-js world-html world-css
  });
 },
};
console.log(obj_cart.show());

Extension of this 2

The situation here is only for some functions

Some callback functions can pass two parameters, then the second parameter will point to the object this to the callback function, you can get the object

let grades = {
    
    
 class: 'class 4-',
 mark: [11, 22, 33],
 appear: function () {
    
    
  this.mark.map(function (item) {
    
    
   console.log(this.class + item);

   // 这里将this作为第二个参数传给了map()
  }, this);
 },
};
console.log(grades.appear()); // class 4-11  class 4-22  class 4-33

Guess you like

Origin blog.csdn.net/michaelxuzhi___/article/details/115059008