【问题标题】:How to properly delegate an object?如何正确委托对象?
【发布时间】:2013-12-20 00:14:45
【问题描述】:

我想创建自己的 DOM 对象类型:

var Obj = function(id) {
  this.id = id;
  this.constructor.prototype = document.getElementById(id);
};

var x = new Obj("a_div"); //Success
alert(x.type); //Successfully alert "div"
x.innerHTML = "TEST"; //This does not update the actual div html on the page!!!

我希望对这个对象的任何函数调用都会被转发到实际的 DOM 对象。我怎样才能做到这一点?

【问题讨论】:

  • 这似乎不像你描述的那样工作(div 没有被提醒):jsfiddle.net/y3Je3/1
  • 您是否要扩展 div 对象?我不认为你可以。
  • @RocketHazmat 我想委托它..
  • @texasbruce:我不太确定你能做到。
  • @AndrewWhitaker 当我在 chrome 上测试时它起作用了。将重新测试

标签: javascript oop


【解决方案1】:

我在代码方面取得了部分成功

var Obj = function(id) {
  this.id = id;
  this.__proto__ =  document.getElementById(id);
};

但是当尝试在 Firefox 中读取/写入 innerHTML 时,它会显示错误:
TypeError: 'innerHTML' getter called on an object that does not implement interface Element. 所以我猜浏览器 DOM 实现存在一些限制。

【讨论】:

    【解决方案2】:

    为什么不做这样的事情:

    var Obj = function(id) {
      return document.getElementById(id);
    };
    

    您基本上将 getElementById 别名为 Obj 以用于速记符号。诚然,您的 x.type 无法按预期工作,但我确信可以修复。

    您可以在此处查看示例:http://jsfiddle.net/Nemesis02/HwxDL/

    更新:

    var Obj = function(id) {
      var el = document.getElementById(id);
      el.type = function() {
            // do something here
      }
      return el;
    };
    

    【讨论】:

    • 因为我想将更多的函数和数据包装到对象中
    猜你喜欢
    • 2013-11-26
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多