私有变量由全局函数访问

时间:2013-04-28 04:28:39

标签: javascript inheritance

我在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]
});

我的怀疑是:

  1. 任何未声明的变量(如B)都将在全局范围内。是否通过B访问privateVariable是不好的编程风格? (因为,不能像那样访问privateVariable。) 如果是这样,为什么javascript允许这样的定义和访问。

  2. 我想要继承C和D.但是它不适合我吗?哪里出错了?

  3. 为了有趣的目的,我尝试了crockford page中给出的经典继承,但是专业人士是否会在生产代码中使用经典继承?是否建议这样做,(因为总的来说,crockford在他的日子里试图实施经典继承感到遗憾)

1 个答案:

答案 0 :(得分:1)

关于你的第一个问题:在严格模式下不再可能。

第二个问题: Scope.inherits(A)A的所有属性添加到Scope,而不是this。所以当时不存在this.C。您必须先致电Scope.inherits(A) ,然后才能创建Scope的新实例。

D()调用名为D的函数。但是没有这样的功能。您只有A.prototype.D。如果要调用此方法,可以使用this.D()执行此操作。再次:this.D()当时不存在。

第三个问题: 这是个人选择。我建议 - 对于任何语言 - 使用该语言而不是模拟其他语言。

相关问题