2013-12-03 53 views
4

我要创造我自己的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对象。我怎样才能做到这一点?

+0

这似乎并没有工作,你描述('div'不惊动)的方式: –

+0

你想扩展在div对象http://jsfiddle.net/y3Je3/1/?我不认为你可以。 –

+0

@RocketHazmat我想委托它.. – texasbruce

回答

0

为什么不只是做这样的事情:

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; 
}; 
+0

因为我想换更多的功能和数据来更新我的评论的对象 – texasbruce

+0

。 – Nemesis02

+0

这将宣告我每次创建对象时添加的功能.. – texasbruce

0

我有代码部分的成功

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

但是当尝试读/写的innerHTML在Firefox中显示错误:
TypeError: 'innerHTML' getter called on an object that does not implement interface Element. 所以我想有通过浏览器的DOM一些限制实现。