0

I am working on a tool that creates GUIs by assembling it from smaller pieces of the user's choice. these smaller pieces are html elements that are created programaticly.

with efficiency in mind I wondered if these elements could share a prototype, just like plain javascript objects can.

this is my method for extending:

var extend = function(o){
    var F = function(){};
    F.prototype = o;
    var x = new F();
    x._proto_ = o;
    return x;
};

which is the same as Object.create(), it just keeps a reference to the prototype as in Mozilla.

so this works fine for plain objects:

var a = { x: 0, y: 1};
var b = extend(a);
b.y; // 1 

but when I try to use it for actual html element it fails:

var a = document.createElement("div");
a.whatever = //whatever..
var b = extend(a);
document.body.appendChild(b); //this throws an error.

the error reads: "An attempt was made to reference a Node in a context where it does not exist."

what's the deal? is it not possible to do this with html elements?

any thoughts are appreciated..

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Ido Ofir
  • 207
  • 2
  • 8
  • 2
    Elements are native objects. They aren't pure JavaScript and modifying their prototype isn't always predictable. Why don't you create a jQuery-like element wrapper instead? That way, you leave the element intact and just extend your wrapper's prototype all you want. – Blender Dec 30 '12 at 10:06
  • Perhaps you need to look at this https://developer.mozilla.org/en-US/docs/JavaScript-DOM_Prototypes_in_Mozilla – mplungjan Dec 30 '12 at 11:02
  • mplungjan - from what I understand from ur link, what I'm trying to do is unnessecery since all elements of the same html type allready share a prototype. does that sound right? – Ido Ofir Dec 30 '12 at 11:33
  • Blender - thats a good idea, I need to get a bit more into JQuery to understand what those 'wrappers' are.. do you happen to know of a good article about that? – Ido Ofir Dec 30 '12 at 11:34

1 Answers1

1

Because b, that you get after extend call, is not a DOM element, it's an object, that holds reference to DOM element in prototype.

P.S. Are you sure that you need x.prototype = o; line in extend function?

Hott Dogg
  • 11
  • 1
  • changed that to '_proto_' for clearity. it just holds a reference to the prototype so it can be accessed dynamically later on. – Ido Ofir Dec 30 '12 at 11:28
  • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create, see the end of article I think you don't need that line at all – Hott Dogg Dec 30 '12 at 12:09