具有相同类的调用函数的JavaScript范围

时间:2013-01-16 06:31:36

标签: javascript scope

它可以正常工作如下:

function A() {
}

A.prototype.f1 = function() {
  alert('f1');
};

A.prototype.f2 = function() {
  // calls f1
  A.prototype.f1();
};

var a = new A();
a.f2(); // alert f1 correctly

但是有一个函数B使A未定义到窗口范围,但可以在B范围内访问:

function A() {
}

A.prototype.f1 = function() {
  alert('f1');
};

A.prototype.f2 = function() {
  // calls f1
  A.prototype.f1();
};

function B() {
  var PrivateA = null;

  this.makePrivate = function() {
    PrivateA = A;     // private access
    A = undefined;        // undefined with window object
  };

  this.callA = function() {
    var a = new PrivateA();
    a.f2();               // it calls A.prototype.f1();, but A is undefined now
  };
}

var b = new B();
// expect to accessible
var a = new A();

b.makePrivate();
// expect to inaccessible to window
alert(typeof A);         // expect to be 'undefined'
b.callA();               // expect to alert 'f1', which not works now since A is undefined

我希望在调用B之前使A可访问,而在调用B时不可访问。

请提供一些建议。

1 个答案:

答案 0 :(得分:0)

您可以将B设置为如下所示:

function B() {
    var PrivateA;  // It's not accessible from outside of B's scope

    this.makePrivate = function() {
        PrivateA = A;  // Still in B's scope, so it works
        A = undefined;
    };

    this.callA = function() {
        var a = new PrivateA();  // So is this
        a.f2();
    };
}

以下是我运行时会发生的事情:

> var b = new B();
> A
function A() {
    this.f1 = function() {
        alert('f1');
    };

    this.f2 = function() {
        // calls f1
        this.f1();
    };
}
> b.makePrivate();
> A
undefined
> b.callA();  // I get an alert that says 'f1'