在使用创建的对象

时间:2016-11-19 01:41:11

标签: javascript function object properties undefined

我知道这可能是一个愚蠢的问题,但我是javascript的新手,所以会很感激一些指导。

我创建了以下notificationSocketEventHandler对象:

const notificationSocketEventHandler = Object.create(socketHandlerProto, {
  validators: {
    created: [],
    destroyed: [],
    loadedFromSocket: [],
    updated: [],
    addedto: {
      relation: []
    },
    removedfrom: {

    }
  },
  created: function (data) {
    if (this.validateProfileData(data, validators.created)) {} else {}
  },
  destroyed: function (data) {},
  updated: function (data) {},
  loadedFromSocket: function (data) {
      console.log('Loaded from socket')
      console.log(data)
  }
})

此事件处理程序用于侦听来自套接字的通知 所以并设置如下

$.globals.socket.on('notifications',notificationSocketEventHandler);

事件原型定义如下:

$.globals.socket = {
  events: {},
  on: function (attr, func) {
    if (!attr) return false
    this.events[attr] = this.events[attr] || [];
    this.events[attr].push(func)
    return true
  },
  remove(attr, func) {
    if (!events[attr]) return false

    this.events[attr].forEach(function (f, indx) {
      if (f === func) {
        events[attr].slice(indx, 1)
      }
    })
  },
  trigger: function (attr, thisArg, paramArgs) {
    if (Array.isArray(attr) && attr.length) {
      var obj = this.events[attr[0]]
      for (var i = 1; i < attr.length; i++) {
        if (!obj) return
        obj = obj[attr[i]]
      }
      if (typeof obj == 'function') obj.apply(thisArg, paramArgs)
      if (Array.isArray(obj)) {
        obj.forEach(function (c) {
          if (typeof c == 'function') c.apply(thisArg, paramArgs)
        })
      }
      return
    }
    if(this.events[attr]){
      console.log(this.events[attr])
      this.events[attr].forEach(function (f) {
        if (typeof f === 'function')
          f.apply(thisArg, paramArgs)
      })
    }
  }
}

我遇到的问题是,在notificationSocketEventHandler对象传递给$.globals.socket.on函数并最终推入事件对象后,notificationSocketEventHandler的属性如{{1}在传递给created函数之前被定义为函数的{},destroyedloadedFromSocket突然变为“未定义”。一旦在事件对象内,为什么会这样?

1 个答案:

答案 0 :(得分:2)

Object.create有点混乱 - 你不能使用普通对象作为第二个参数,它必须是属性描述符&#39;的对象。为了正常工作,您的代码需要按以下格式进行格式化:

const notificationSocketEventHandler = Object.create(socketHandlerProto, {
  'validators': {
    value: {
     'created': {
          value: []
      },
      'destroyed': {
          value: []
      },
      'loadedFromSocket': {
           value: []
      }
    }    
  }
});

除非你对这些属性进行迭代,否则它将变得单调乏味。你最好避免使用Object.create并正常制作一个对象:

const notificationSocketEventHandler = {
   created: [],
   destroyed: [],
   etc...
}

或将属性添加到构造函数的原型中(除此之外,人们通常会使构造函数名称以大写字母开头,因此它们很明显是构造函数 - 可以节省您必须添加的内容&#39; Proto&#39;在一个名称的末尾。无论如何):

var SocketHandler = function {
    this.created = [];
    this.destroyed = []
    etc...
}

const notificationSocketEventHandler = new SocketHandler

var SocketHandler = {};
SocketHandler.prototype.created = [];
SocketHandler.prototype.destroyed = [];
etc...