0
点赞
收藏
分享

微信扫一扫

js 通过常量改变this指针

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    let lesson = {
      site: "李四",
      lists: ["js", "css", "mysql"],
      show: function () {
        console.log(this, this.site, this.lists);
        const self = this; //这个this, 就是lesson了
        // 方式一: self = this
        // return this.lists.map(function (value) {
        //   console.log(this.site); //直向了window,是读不到的
        //   console.log(self); //{site: '李四', lists: Array(3), show: ƒ}
        //   return `${self.site}-${value}`;
        // });

        //  方式一: 改变函数的指针
        return this.lists.map(function (value) {
          return `${this.site}-${value}`;
        }, this);
      },
    };
    console.log(lesson.show());
  </script>
</html>

举报

相关推荐

0 条评论