JavaScriptで継承とスコープアクセスを学んでいます。そこで、以下のサンプルプログラムを作成しました。
var A = function(){
var privateVariable = 'secretData';
function E(){
console.log("Private E");
console.log("E reads privateVariable as : " + privateVariable);
};
B = function(){
console.log("GLOBAL B");
console.log("B reads privateVariable as : " + privateVariable);
} ;
this.C = function(){
console.log("Privilaged C");
console.log("C reads privateVariable as : " + privateVariable);
};
};
A.prototype.D = function(){
console.log("Public D, I can call B");
B();
};
A.F = function(){
console.log("Static D , Even I can call B");
B();
};
var Scope = function(){
var a = new A();
Scope.inherits(A); // Scope inherits A
E(); // private Method of A , Error : undefined. (Acceptable because E is private)
this.C(); // private Method of A, Error : undefined.
D(); // public Method of A, Error : undefined.
}
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Function.method('inherits', function (parent) {
console.log("I have been called to implement inheritance");
//Post will become lengthy. Hence,
//Please refer [crockford code here][1]
});
私の疑問は次のとおりです。
B のような宣言されていない変数はグローバル スコープになります。B を介して privateVariable にアクセスすることはプログラミングのスタイルが悪いかどうか? (なぜなら、privateVariable はそのようにアクセスできないからです。) もしそうなら、なぜ javascript がそのような定義とアクセスを許可するのか。
CとDを継承したいのですがうまくいきませんか?どこで間違ったのですか?
楽しみのために、crockford のページにあるように古典的な継承を試してみましたが、専門家は製品コードで古典的な継承を使用するでしょうか? そうすることが賢明かどうか、(結論として、クロックフォードは初期に古典的な継承を実装しようとしたことを後悔しているため)