0

它可以正常工作,如下所示:

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 时使 A 不可访问。

请给一些建议。

4

1 回答 1

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'
于 2013-01-16T06:52:41.120 回答