2016-03-05 81 views
0

我不知道這是可能的,在所有的,怎麼給過this article我很好奇,怎麼一個功能,如:問題關於工廠函數的概念

export default() => { 
    let _foo = ''; 

    return { 
     set foo(x) { 
      if (x === undefined) { 
       _foo = this.someFN(); 
      } else { 
      _foo = x; 
      } 
     }, 

     get foo() { 
      return _foo; 
     }, 

     someFN() { 
     return 'hello' 
     } 
    } 
} 

有一個概念,該文章認爲,在工廠功能中沒有「引用此」。如果是這種情況,你如何將多個工廠功能連接在一起?

比如我在哪裏我已經寫了,讓你可以鏈方法工廠功能的概念工作,一個例子是:

const fooBar = FooBar(); 

fooBar.someMethod().someOtherMethod(); 

這工作,因爲我回到this您是否在工廠功能中避免「this」?和**工廠的功能是否只有一種方法?

所以在我上面的例子中,在那裏有someFN()會是錯誤的嗎?

+0

這是一個例子,它不是一個有問題的代碼,它的問題已經解決了。你能否以我可以投票或接受的方式回答問題?謝謝。 – TheWebs

回答

1

有沒有硬性規定,你不能在工廠功能中使用this。但是,如果你想避免它,只記得你的對象在一個變量和使用,而不是(這也避免了與功能問題被稱爲用錯this):

export default() => { 
    let _foo = ''; 
    let obj = { 
     set foo(x) { 
      if (x === undefined) { 
       _foo = this.someFN(); 
      } else { 
      _foo = x; 
      } 
     }, 

     get foo() { 
      return _foo; 
     }, 

     someFN() { 
     return 'hello' 
     }, 

     chainableMethod1() { 
      // Do something, then 
      return obj; 
     }, 

     chainableMethod2() { 
      // Do something else, then 
      return obj; 
     } 
    }; 

    return obj; 
}; 

用法:

theModule.chainableMethod1().chainableMethod2();