簡體   English   中英

ES6類變量超出范圍?

[英]ES6 Class Variables Out of Scope?

剛剛切換到運行io.js的ES6。

我正在編寫一些類代碼,但是出現意外錯誤。

'use strict';

var _ = require('lodash');

class Country {

  constructor(blocked) {
    this.blocked = ['USA'];
  }

  ok(input) {
    console.log('Receiving...',input['country']);
    console.log('Blocked:', this.blocked);
    if(_.includes('USA', input['country'])) {
      return -1;
    }
    return 0;
  }

}

module.exports = Country;

無論出於什么原因, 除了 this.blocked類變量之外 ,其他所有東西都運行良好。

當我進行控制台日志記錄時,它顯示為Blocked: undefined

關於這里發生的事情有什么想法嗎?

加成

我在另一個類中調用該函數,如下所示...

var Country  = require('./filters/country.js');
var country  = new Country();

class FilterClassifier {

    constructor() {
      var self = this;
      self.filters = [country.ok];
    }

    userFilter(params) {

      var self = this;

      var input = {
        country   : params.country,
      };

      console.log(self.filters[0](input));
    }

}

module.exports = FilterClassifier;

如注釋中所述,調用函數的方式刪除了函數的上下文。

self.filters = [country.ok];

接着

console.log(self.filters[0](input));

意味着this里面ok將不country 你需要做

self.filters = [country.ok.bind(country)];

要么

self.filters = [() => country.ok()];

我建議你閱讀了this在JavaScript。 在這種特殊情況下的簡短答案是, this是根據調用函數的方式定義的。

var a = {};
a.fn = function(){};

var b = {};
b.fn = a.fn;

b.fn();

調用b.fn()this函數內部為b 這是因為當使用foo.bar()形式調用函數時, this函數內部的對象被定義為調用該函數的對象( foo )。 就你而言

self.filters[0]();

這意味着, this里面你ok功能實際上是self.filters出於同樣的原因。

如果你有一個具體的this是重要的,它是你的責任,以確保你繞過一個功能,您將通過設置適當的功能this 使用fn.bind(foo)將返回一個新函數,該函數在調用時使用給定的this調用fn

它看起來像this.blocked的作用范圍是constructor函數, thisok沒有被叫標識blocked

編輯 :我錯了,謝謝Pointy。 為了幫助那些偶然發現這篇文章的人,我不會刪除我的錯誤答案,而是分享我學到的東西。 大衛,在評論中,您要求找到一種解決方法。 this可以替換為設變量 ,以避免混淆,或使用thisbind()當一個函數被調用。

class Country {

  // variable scoped to class with let
  // set blocked = value in constructor
  // should not need 'this.' nor 'bind()'

  let blocked = [];

... 
}

確定this說:”你不得不默認 this綁定:不確定。 您希望使用隱式綁定,並希望顯式綁定可以與country.ok.bind(country)

進一步的閱讀說明了胖箭頭=>var self = this; 使this令人困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM