Tuesday, April 10, 2012

How can I make several Elements when extending a DIV-Element?

I am trying to "extend" a DIV via Javascript by using a newly created div as prototype of my object.



As I understand Javascript, on creating a new instance of my Object via "new", the prototype-object is copied, assigned to "this" an then the function is executed (as the constructor).



Everything seems to work, except that whenever I create another object, and add it to the DOM, it "replaces" the original div. To be more exact: The constructor always changes the same div.



Using MyTest.prototype = document.createElement("div"); gives me the described behavior, the two commented lines after that in my code example are what I also tried, but to no avail.



I know trying to extend the DOM is frowned upon, but I want to understand this behavior, because I thought I knew how prototypes work and this simply does not fit my idea.



Here is a minimal example of what I am trying to do:



<!DOCTYPE html>
<html>
<head>
<title>Div-Prototype-Test</title>
<script type="text/javascript">

var height = 20;
var top = 0;

function MyTest() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);

this.style.backgroundColor = "rgb("+ r +","+ g +","+ b +")";
this.style.position = "absolute";
this.style.width = "500px";
this.style.height = height + "px";
this.style.top = top + "px";

top += height;

document.getElementsByTagName("body")[0].appendChild(this);
}

MyTest.prototype = document.createElement("div");
// MyTest.prototype = document.createElement("div").cloneNode(true);
// MyTest.prototype = new Element();

window.addEventListener(
"load",
function() {
var a = new MyTest();
var b = new MyTest();
var c = new MyTest();
var d = new MyTest();
}
);

</script>
</head>
<body>
</body>
</html>


PS: Because of a certain Javascript-Framework my search for anything that changes the prototype in Javascript always resulted in hundreds of results that had nothing to do with my problem - please tell me if I missed a question that already discusses this.





No comments:

Post a Comment