【问题标题】:Private Variables are accessed by Global functions私有变量由全局函数访问
【发布时间】:2013-04-28 04:28:39
【问题描述】:

我在 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 很遗憾在他早期尝试实现经典继承)

【问题讨论】:

  • @downvoter 为什么投反对票?有什么原因吗?

标签: javascript inheritance


【解决方案1】:

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

第二个问题: Scope.inherits(A)A 的所有属性添加到Scope,而不是this。所以this.C当时不存在。您必须在创建Scope 的新实例之前调用Scope.inherits(A)

D() 调用一个名为D 的函数。但是没有这样的功能。你只有A.prototype.D。如果你想调用这个方法,你可以使用this.D()。再说一遍:this.D() 那时不会存在。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多