我在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中给出的经典继承,但是专业人士是否会在生产代码中使用经典继承?这样做是否可取,(因为总而言之,crockford 很遗憾在他早期尝试实现经典继承)