第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

全部開發(fā)者教程

JavaScript 入門教程

this 使用問題

大部分開發(fā)者都會合理、巧妙的運(yùn)用 this 關(guān)鍵字。

初學(xué)者容易在 this 指向上犯錯,如下面這個 Vue 組件

<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
  // 發(fā)送post請求
  const post = (cb) => {
    // 假裝發(fā)了請求并在200ms后返回了服務(wù)端響應(yīng)的內(nèi)容
    setTimeout(function() {
      cb([
        {
          id: 1,
          name: '小紅',
        },
        {
          id: 2,
          name: '小明',
        }
      ]);
    });
  };

  new Vue({
    el: '#app',
    data: function() {
      return {
        list: [],
      };
    },
    mounted: function() {
      this.getList();
    },
    methods: {
      getList: function() {
        post(function(data) {
          this.list = data;
          console.log(this);
          this.log(); // 報錯:this.log is not a function
        });
      },

      log: function() {
        console.log('輸出一下 list:', this.list);
      },
    },
  });
</script>

這是初學(xué) Vue 的同學(xué)經(jīng)常碰到的問題,為什么這個 this.log() 會拋出異常,打印了 this.list 似乎也是正常的。

這其實(shí)是因?yàn)閭鬟f給 post 方法的回調(diào)函數(shù),擁有自己的 this,有關(guān)內(nèi)容可以查閱 this章節(jié)

不光在這個場景下,其他類似的場景也要注意,在寫回調(diào)函數(shù)的時候,如果在回調(diào)函數(shù)內(nèi)要用到 this,就要特別注意一下這個 this 的指向。

可以使用 ES6 的箭頭函數(shù) 或者將需要的 this 賦值給一個變量,再通過作用域鏈的特性訪問即可:

<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
  // 發(fā)送post請求
  const post = (cb) => {
    // 假裝發(fā)了請求并在200ms后返回了服務(wù)端響應(yīng)的內(nèi)容
    setTimeout(function() {
      cb([
        {
          id: 1,
          name: '小紅',
        },
        {
          id: 2,
          name: '小明',
        }
      ]);
    });
  };

  new Vue({
    el: '#app',
    data: function() {
      return {
        list: [],
      };
    },
    mounted: function() {
      this.getList();
    },
    methods: {
      getList: function() {

        // 傳遞箭頭函數(shù)
        post((data) => {
          this.list = data;
          console.log(this);
          this.log(); // 報錯:this.log is not a function
        });

        // 使用保留 this 的做法
        // var _this = this;
        // post(function(data) {
        //   _this.list = data;
        //   console.log(this);
        //   _this.log(); // 報錯:this.log is not a function
        // });
      },

      log: function() {
        console.log('輸出一下 list:', this.list);
      },
    },
  });
</script>

這個問題通常初學(xué)者都會碰到,之后慢慢就會形成習(xí)慣,會非常自然的規(guī)避掉這個問題。

索引目錄