Ad

Console Logging "this" Returns "null"

I am trying to create a flux store for a React app I am building. I am using an object-assign polyfill npm package and Facebook's Flux library.

Initially I was getting the error "Cannot read property '_data' of null' error in the console which was refering to var currIds = this._data.map(function(m){return m.id;});. That method is currently the only one being called directly. I then did console.log(this) which returned "null".

I find this strange. What is going on?

My code:

var Assign = require('object-assign');
var EventEmitterProto = require('events').EventEmitter.prototype;
var CHANGE_EVENT = 'CHANGE';

var StoreMethods = {

init: function() {},
set: function (arr) {
console.log(this);
    var currIds = this._data.map(function(m){return m.id;});

    arr.filter(function (item){
      return currIds.indexOf(item.id) === -1;
    }).forEach(this.add.bind(this));

},
add: function(item){
  console.log(this);
    this._data.push(item);
},
all: function() {
    return this._data;
},
get: function(id){
   return this._data.filter(function(item){
       return item.cid === id;
   })[0];
},
addChangeListener: function(fn) {
    this.on(CHANGE_EVENT, fn);
},
removeChangeListener: function(fn) {
    this.removeListener(CHANGE_EVENT, fn);
 },
 emitChange: function() {
    this.emit(CHANGE_EVENT);
 },
 bind: function(actionType, actionFn) {
    if(this.actions[actionType]){
        this.actions[actionType].push(actionFn);
    } else {
        this.actions[actionType] = [actionFn];
    }
}
};

exports.extend = function(methods) {
var store = {
_data: [],
actions: {}
};

Assign(store, EventEmitterProto, StoreMethods, methods);
store.init();

require('../dispatcher').register(function(action){
   if(store.actions[action.actionType]){
       store.actions[action.actionType].forEach(function(fn){
        fn.call(null, action.data);
       })   
   }
  });

  return store;
 };
Ad

Answer

I can't see where set is called, however your this can be null if the function is invoked through call (see here) or apply, and your first argument is null. This also happens in your require.register callback:

fn.call(null, action.data) //First parameter is your 'this'.
Ad
source: stackoverflow.com
Ad