I have the following code for a mini framework. How do i “bulletproof” my code so that a possible delinquent developer will not break it? I summarized what the code does in the comments, and here’s a demo for clarification
var kit = (function() {
'use strict';
//internal cache
var internal = {
core: {}
}
//external interface for extensions
//let's say we provide a hook for error handling from the core
var external = {
core: {
error: {
addListener: function(callback) {
callback();
}
}
}
}
//externally available options
var core = {
//build extension by creating an instance of the passed function
//providing it the core interface, and
//then store the instance in the cache
extend: function(extensionName, extensionDefinition) {
var newExtension = new extensionDefinition(external.core)
internal.core[extensionName] = newExtension;
}
};
//expose
return {
core: {
extend: core.extend
},
_internal: internal,
_external: external
}
}());
//let's say two developers built these extensions
//developer1 builds his code
kit.core.extend('extension1', function(core) {
core.error.addListener(function() {
alert('test');
})
//developer1 intentionally kills the whole error interface
core.error = null;
});
//now, the other scripts cannot use the error interface
//because some delinquent developer killed it
kit.core.extend('extension2', function(core) {
//core.error is no more!
core.error.addListener(function() {
alert('test');
})
});
how do i do this so that every extension has an isolated “copy” of the core external functions so no matter what they do to it, it does not affect the other extensions?
A side question, if i may add: Is there a better way/approach to structuring this code?
If you are trying to make your code safe from accidental interferance, then:
is not how to do it. You don’t know what window references in the global context (it may not exist at all), the only reference you know is safe is this, which must reference the global object, so:
is safer.
Nothing can access your code inside the IIFE, so it is as safe as javascript can be, but it is certainly not secure. Any system that delivers its source to the client is inherently insecure.