2017-03-03 51 views
0

因此,我創建像一個基於原型的對象:有問題「這個」在原型對象

// constructor 
const MyFactory = function() { 
    this._myProperty = { 
     MyType1: '...', 
     MyType2: '...' 
    }; 

    this._converters = [{ 
     name: 'X' 
     outgoingConverter: this._convertToX 
    }, 
    { 
     name: 'Y' 
     outgoingConverter: this._convertToY 
    }]; 
    // ... 
} 

MyFactory.prototype._convertToX = function (myObjArray) { 
    console.log(this._myProperty); // undefined 
    const convertedObjArray = _.map(myObjArray, (obj) => { 
     console.log(this._myProperty); // undefined 
     const MyObject = this._myProperty[obj.type]; // throws error 
     return MyObject ? new MyObject() : undefined; 
    }); 
    //... 
}; 

MyFactory.prototype._dispatch = function (myObjArray) { 
    _.forEach(this._converters, (converter) => { 
     converter.outgoingConverter(myObjArray); 
    }); 
}; 

// somewhere in this code I am calling this._dispatch(someObjArray) 

我試圖從.map()函數內部訪問this._myProperty,但我得到:

TypeError: Cannot read property 'MyType1' of undefined

我認爲在我的代碼中有this context有問題。
從我的理解ES6 arrow functions保留this封閉的上下文,所以我不明白什麼是錯的。

問題
爲什麼this._myProperty不確定我_convertToX功能?
如何從那裏訪問_myProperty

回答

1

當您致電converter.outgoingConverter(myObjArray);outgoingConverter是對_convertToX的參考。但是,thisconverter!在構造函數中,您可能需要使用this._convertToX.bind(this)來強制this

+0

非常感謝!不知道我怎麼看不到......現在我改變了我的'_converters'數組:'outgoingConverter:this._convertToX.bind(this)' – lenny

+0

@lenny你說的對,箭頭函數保留'this'。但是,當你有錯誤的「這個」時,這並沒有幫助;) –