为Javascript对象分配函数

Assigning functions to a Javascript Object

本文关键字:函数 分配 对象 Javascript      更新时间:2023-09-26

我在JS程序中有特定的图结构,其中每个节点都有与其相关的特定函数。

图结构

var g = {
  "alpha_1" : getNode("alpha"),
  "beta_1" : getNode("beta")
 ....
}

getNode()函数

var getNode = function (type) {
        var obj = {
            'metaType': type,
            'config': Object,
            'data': {
                'loc': {'x': '', 'y': ''},
                'args': {'keys': [], 'values': []},
                'return': []
            },
            'in': [],
            'true': [],
            'false': [],
            'inLineId': [],
            'outLineTrueId': [],
            'outLineFalseId': []
            //'prototype': Object.prototype
        };

        switch (type) {
            case 'alpha':
                obj.data.args.keys.push('dataStore', 'filters', 'limit', 'data');
                obj.data.args.values['dataStore'] = '';
                obj.data.args.values['limit'] = 'FALSE';
                obj.data.args.values['data'] = 'FALSE';
                obj.data.args.values['filters'] = [];
                /**
                 * @param valueObj :{}  JSON Object with fields from, value, type
                 */
                obj.config.defineProperty(Object.prototype, 'setDatastore', {
                    value: function (valueObj) {
                        obj.data.args.values['dataStore'] = valueObj;
                    },
                    enumerable: false,
                    configurable: true,
                });
                /**
                 * @param valuesArray :[]  Array with fields from, value, type
                 */
                obj.config.defineProperty(Object.prototype, 'setReturnValues', {
                    value: function (valueArray) {
                        obj.data.args.values['return'].push.apply([], valueArray);
                    },
                    enumerable: false,
                    configurable: true,
                });
        case 'beta':
            /**
             * @param key
             * @param op =/>=/!=/<=/</>
             * @param valueObj :{}  JSON Object with fields from, value, type
             * @param next
             */
            obj.config.defineProperty(Object.prototype, 'addFilter', {
                value: function (key, op, valueObj, next) {
                    obj.data.args.values['filters'].push(
                        {
                            'key': key,
                            'op': op,
                            'value': valueObj,
                            'next': next
                        }
                    );
                },
                configurable: true,
                enumerable: false
            });
..

    }
  return obj;
}

然后我尝试以以下方式访问定义的函数,

g.alpha.config.setDatastore({"a":"b"});

但它给了我一个错误。

未捕获类型错误:g.alpha_1.config.setDatastore不是函数(…)

有人能帮我解决这个问题吗?

看看Object.defineProperty():

Object.defineProperty(obj, prop, descriptor)

参数

obj要在其上定义属性的对象

prop要定义或修改的属性的名称。

descriptor正在定义或修改的属性的描述符。

obj.config.defineProperty(Object.prototype, ...)会将属性添加到Object.prototype.

您正在寻找的是:Object.defineProperty(obj.config, ...)

您还需要将'config': Object,更改为'config': new Object(),

var getNode = function(type) {
  var obj = {
    'metaType': type,
    'config': new Object(),
    'data': {
      'loc': {
        'x': '',
        'y': ''
      },
      'args': {
        'keys': [],
        'values': []
      },
      'return': []
    },
    'in': [],
    'true': [],
    'false': [],
    'inLineId': [],
    'outLineTrueId': [],
    'outLineFalseId': []
      //'prototype': Object.prototype
  };
  switch (type) {
    case 'alpha':
      obj.data.args.keys.push('dataStore', 'filters', 'limit', 'data');
      obj.data.args.values['dataStore'] = '';
      obj.data.args.values['limit'] = 'FALSE';
      obj.data.args.values['data'] = 'FALSE';
      obj.data.args.values['filters'] = [];
      /**
       * @param valueObj :{}  JSON Object with fields from, value, type
       */
      Object.defineProperty(obj.config, 'setDatastore', {
        value: function(valueObj) {
          obj.data.args.values['dataStore'] = valueObj;
        },
        enumerable: false,
        configurable: true,
      });
      /**
       * @param valuesArray :[]  Array with fields from, value, type
       */
      Object.defineProperty(obj.config, 'setReturnValues', {
        value: function(valueArray) {
          obj.data.args.values['return'].push.apply([], valueArray);
        },
        enumerable: false,
        configurable: true,
      });
    case 'beta':
      /**
       * @param key
       * @param op =/>=/!=/<=/</>
       * @param valueObj :{}  JSON Object with fields from, value, type
       * @param next
       */
      Object.defineProperty(obj.config, 'addFilter', {
        value: function(key, op, valueObj, next) {
          obj.data.args.values['filters'].push({
            'key': key,
            'op': op,
            'value': valueObj,
            'next': next
          });
        },
        configurable: true,
        enumerable: false
      });
  }
  return obj;
}
var g = {
  "alpha_1": getNode("alpha"),
  "alpha_2": getNode("alpha"),
  "beta_1": getNode("beta")
}
g.alpha_1.config.setDatastore({
  "a": "b"
});
g.alpha_2.config.setDatastore({
  "a": "c"
});
//output
document.body.innerHTML = JSON.stringify(g.alpha_1.data.args.values['dataStore']);
document.body.innerHTML += "<br>" + JSON.stringify(g.alpha_2.data.args.values['dataStore']);