javascript - 实现任意对象的通用、轻量级且不显眼的标记?

标签 javascript delegation

注意: 标题为的小节中的 Material  背景 不是必需的。问题的完整描述已完全包含在前面的段落中。

我想实现一种通用的、轻量级的、“不引人注目”的方式来“标记”任意对象。

更具体地说,我想定义(抽象)函数 tag 的等效项。 , isTagged ,和getTagged ,这样:

  1. isTagged(t)true当且仅当ttag(o) 返回的值,对于某些对象 o ;
  2. getTagged(tag(o))o 相同,对于每个对象o ;
  3. 如果 t = tag(o) ,然后tag(t)应与 t 相同;
  4. 上述 (1)、(2) 和 (3) 中描述的行为以及涉及 === 的严格身份测试除外, tag(o)o应该以同样的方式表现。

[编辑:另一项要求是实现不应修改 Object类,也不是任何其他标准类,以任何方式。]

例如:

>>> isTagged(o = "foo")
false
>>> isTagged(t = tag(o))
true
>>> getTagged(t) === o
true
>>> tag(t) === t
true
>>> t.length
3
>>> t.toUpperCase()
"FOO"

下面我将尽力解决这个问题。它(几乎)是通用的,但是,很快就会清楚,它绝不是轻量级! (而且,它还没有完全满足上面的要求4,所以它并不像我希望的那样“不引人注目”。而且,我对其“语义正确性”有严重怀疑。)

此解决方案包括包装对象 o被标记为“代理对象”p ,并复制 o所有属性(无论是“拥有”还是“继承”)至p .

我的问题是:

is it possible to achieve the specifications given above without having to copy all the properties of the tagged object?


背景

这是上面提到的实现。它依赖于实用函数getProperties ,其定义(FWIW)在最后给出。

function Proxy (o) { this.__obj = o }

function isTagged(t) {
  return t instanceof Proxy;
}

function getTagged(t) {
  return t.__obj;
}

var tag = (function () {
  function _proxy_property(o, pr) {
    return   (typeof pr === "function")
           ? function () { return pr.apply(o, arguments) }
           : pr;
  }

  return function (o) {
    if (isTagged(o)) return o;

    if (typeof o.__obj !== "undefined") {
      throw TypeError('object cannot be proxied ' +
                      '(already has an "__obj" property)');
    }
    var proxy = new Proxy(o);
    var props = getProperties(o); // definition of getProperties given below
    for (var i = 0; i < props.length; ++i) {
      proxy[props[i]] = _proxy_property(o, o[props[i]]);
    }
    return proxy;
  }
})();

这种方法虽然笨拙,但至少看起来有效:

// requirement 1
>>> isTagged(o = "foo")
false
>>> isTagged(p = tag(o))
true

// requirement 2
>>> getTagged(p) === o
true

// requirement 3
>>> tag(p) === p
true

// requirement 4
>>> p.length
3
>>> p.toUpperCase()
"FOO"

...嗯,几乎;要求(4)并不总是满足:

>>> o == "foo"
true
>>> p == "foo"
false
>>> o == o
true
>>> p == o
false

FWIW,这是函数getProperties的定义,由 tag 使用功能。欢迎批评。 (警告: 我是一个完全无知的 JS 菜鸟,不知道自己在做什么! 使用此功能需要您自担风险!)

function getProperties(o) {
  var seen = {};
  function _properties(obj) {
    var ret = [];
    if (obj === null) {
      return ret;
    }
    try {
      var ps = Object.getOwnPropertyNames(obj);
    }
    catch (e if e instanceof TypeError &&
                e.message === "obj is not an object") {
      return _properties(obj.constructor);
    }
    for (var i = 0; i < ps.length; ++i) {
      if (typeof seen[ps[i]] === "undefined") {
        ret.push(ps[i]);
        seen[ps[i]] = true;
      }
    }
    return ret.concat(_properties(Object.getPrototypeOf(obj)));
  }
  return _properties(o);
}

最佳答案

我认为你把这一切都过于复杂化了。您没有理由需要将标签存储在对象本身上。如果您创建一个使用对象指针作为键的单独对象,不仅可以节省空间,而且可以防止任意对象碰巧具有名为“_tagged”的属性时发生任何意外冲突。

var __tagged = {};

function tag(obj){
    __tagged[obj] = true;
    return obj;
}

function isTagged(obj){
    return __tagged.hasOwnProperty(obj);
}

function getTagged(obj){
    if(isTagged(obj)) return obj;
}

==编辑==

因此,我决定花一点时间创建一个更强大的标记系统。这就是我创建的。

var tag = {
    _tagged: {},

    add: function(obj, tag){
        var tags = this._tagged[obj] || (this._tagged[obj] = []);
        if(tag) tags.push(tag);
        return obj;
    },

    remove: function(obj, tag){
        if(this.isTagged(obj)){
            if(tag === undefined) delete this._tagged[obj];
            else{
                var idx = this._tagged[obj].indexOf(tag);
                if(idx != -1) this._tagged[obj].splice(idx, 1);
            }
        }
    },

    isTagged: function(obj){
        return this._tagged.hasOwnProperty(obj);
    },

    get: function(tag){
        var objects = this._tagged
          , list = []
        ;//var

        for(var o in objects){
            if(objects.hasOwnProperty(o)){
                if(objects[o].indexOf(tag) != -1) list.push(o);
            }
        }

        return list;
    }
}

您不仅可以标记对象,而且实际上可以指定不同类型的标记并以列表的形式检索具有特定标记的对象。让我举个例子。

var a = 'foo'
  , b = 'bar'
  , c = 'baz'
;//var

tag.add(a);
tag.add(b, 'tag1');
tag.add(c, 'tag1');
tag.add(c, 'tag2');

tag.isTagged(a); // true
tag.isTagged(b); // true
tag.isTagged(c); // true

tag.remove(a);
tag.isTagged(a); // false

tag.get('tag1'); // [b, c]
tag.get('tag2'); // [c]
tag.get('blah'); // []

tag.remove(c, 'tag1');
tag.get('tag1'); // [b]

关于javascript - 实现任意对象的通用、轻量级且不显眼的标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18554287/

相关文章:

javascript - 如何使用 jQuery 选择文本区域内的所有 URL?

javascript - 如何计算不同日期的 24 小时格式的两个时间之间的差异?

javascript - DOM异常: The source image could not be decoded

swift delegate - 何时使用弱引用,为什么 'delegate' 为零?

java - 向 Java 程序员解释 Objective-C 委托(delegate)

java - 是否可以将 Kotlin 的代理委托(delegate)与现有的类/对象(即 Arrow 的 Either)一起使用?

javascript - 为什么 .json() 是异步的?

javascript - 如何在谷歌地图图钉上添加文本标签?

C++ 类委托(delegate)构造函数问题

java - 如何将我的 ClassLoader 设置为 JVM 的 ClassLoader 来加载所有类(包括 jar 类)?