繁体   English   中英

私有变量由全局函数访问

[英]Private Variables are accessed by Global functions

我在 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 后悔在他的早期尝试实现经典继承)

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM