Skip to content

Instantly share code, notes, and snippets.

@taseenb
Last active August 29, 2015 13:58
Show Gist options
  • Save taseenb/9941545 to your computer and use it in GitHub Desktop.
Save taseenb/9941545 to your computer and use it in GitHub Desktop.
JS simple extendable instances
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>funky</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
// p5.js core
(function(exports) {
// P is simply a function returning an instance of a p5 sketch
var P = function(name) {
return new p5(name);
};
// p5 constructor: creates a sketch instance
var p5 = function(name) {
// Set default settings
this.settings = {
name: name,
angleMode: 0
};
};
// IMPORTANT! Create a custom prototype
P.prototype = {};
// IMPORTANT! Add it to the sketch instance
// Instances will inherit the p5 prototype:
// all its methods, properties, plugins...
p5.prototype = P.prototype;
// p5 extend()
// Use this function to extend the p5 prototype
P.extend = P.prototype.extend = function(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof p5.prototype[prop] == 'undefined') {
p5.prototype[prop] = obj[prop];
} else if (typeof p5.prototype[prop] != 'undefined') {
throw 'Error\n"' + prop + '" name is already in use.\nPlease use another name for your extension.';
}
}
};
// Make p5 global
exports.p5 = P;
})(window);
// Create a PVector plugin (global)
var PVector = function(x, y, z) {
var settings = this.settings;
function Vector(x, y, z) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
if (settings) {
// Store the p5 sketch object/instance in a var
this.sketchName = settings.name + ', now with PVector!';
this.getAngleMode = function() {
return settings.angleMode;
};
}
}
return new Vector(x, y, z);
};
// Extend p5 with the PVector plugin
p5.extend({'PVector': PVector});
// Create a new sketch
var p = p5('My-sketch');
p.settings.angleMode = 1;
// Create a new PVector
var vec = p.PVector(5); // DO NOT USE new!
//Create a new PVector in the global context
var globalVec = PVector(10);
// TEST
console.log(p); // 'p5 {}'
console.log(p.settings.name); // 'My-sketch '
console.log(vec.sketchName); // 'My-sketch, now with PVector!'
console.log('angleMode === ' + vec.getAngleMode()); // 1
console.log('vector x === ' + vec.x); // 5
console.log('global vector x === ' + globalVec.x); // 10
console.log('global vector sketchName === ' + globalVec.sketchName); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment