Object into Prototype
Moving functions from an Object def into an Object prototype
by David McClelland
JavaScript
// before:
function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
this.sendRopeTo = function(connectedPost) {
this.connectionsTo.push(connectedPost);
};
this.removeRope = function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
};
this.movePost = function(x, y) {
this.x = x;
this.y = y;
};
}
// after:
// Object Definition
function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
}
// prototype functions
Fencepost.prototype = {
removeRope: function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
},
movePost: function(x, y) {
this.x = x;
this.y = y;
},
sendRopeTo: function(connectedPost) {
this.connectionsTo.push(connectedPost);
}
};