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..

4
  • 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. Commented Dec 30, 2012 at 10:06
  • Perhaps you need to look at this developer.mozilla.org/en-US/docs/… Commented Dec 30, 2012 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? Commented Dec 30, 2012 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? Commented Dec 30, 2012 at 11:34

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

changed that to 'proto' for clearity. it just holds a reference to the prototype so it can be accessed dynamically later on.
developer.mozilla.org/en-US/docs/JavaScript/Reference/…, see the end of article I think you don't need that line at all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.