Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 与'有关的问题;这';在原型对象中_Javascript_Prototype_This - Fatal编程技术网

Javascript 与'有关的问题;这';在原型对象中

Javascript 与'有关的问题;这';在原型对象中,javascript,prototype,this,Javascript,Prototype,This,因此,我创建了一个基于原型的对象,如: // constructor const MyFactory = function () { this._myProperty = { MyType1: '...', MyType2: '...' }; this._converters = [{ name: 'X' outgoingConverter: this._convertToX }, {

因此,我创建了一个基于原型的对象,如:

// 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()
函数内部访问
此属性。\u myProperty
,但我得到:

TypeError:无法读取未定义的属性“MyType1”

我认为,我的代码中的
上下文
有问题。
从我的理解来看,保留了
这个
的封闭上下文,所以我不明白出了什么问题

问题
为什么在my
\u convertToX
函数中未定义此属性?

如何从那里访问myProperty?

当您调用
converter.outgoingConverter(myObjArray)时输出转换器
是对
\u convertox
的引用。但是,
转换器
!在构造函数中,您可能希望使用
this.\u convertox.bind(this)
强制
this

非常感谢!不知道我怎么看不到。。。现在我在我的
\u转换器
数组中进行了更改:
outgoingConverter:this.\u convertox.bind(this)
@lenny你说得对,箭头函数保留了
this
。但是,当您使用错误的
☺ ;)