我學習了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 page中給出的經典繼承,但是專業人員是否會在生產代碼中使用經典繼承?無論是建議這樣做,(因爲在最後,爲努力實現他的eary天經典的繼承克羅克福德遺憾)
@downvoter爲什麼downvoted?任何原因? – 2013-04-28 04:43:14