私はミニフレームワークのために次のコードを持っています。私のコードをどのように「防弾」して、未払いの開発者がそれを壊さないようにしますか?私はコードがコメントで何を要約し、ここで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');
})
});
すべての拡張子は、それほど関係なく、彼らはそれに何をすべきか、それをcore
外部関数の単離された「コピー」を持っていないように私はこれをどのように行うかです他の拡張機能には影響しませんか?
私が追加してもいいかどうか:このコードを構造化するより良い方法/アプローチがありますか?
一般的に言えば、JavaScriptを「防弾」することはできません。言語はあまりにも容認されます。ブラウザーが提供する組み込み関数( 'alert()'、 'parseInt()'など)でも任意に置き換えることができます。通常は、展開する前にコードを難読化することが最善の方法です。 – aroth
@aroth私はそれを防ぐのに十分な厚さのケブラーがないことを知っています。しかし、私は破損を分離するためのより良い方法があるかどうかを知りたいと思います。 – Joseph