What does the @private annotation actually do in the Google Closure JavaScript code?

When I put a comment above my variable or function with @privatein it, what does it actually do? I looked through the documentation, but I'm still not sure.

goog.provide('myproject');

/** @private */
myproject.foo = "bar";

I can access it when I open the tools for creating chrome (myproject.foo). AND...

goog.require('myproject');

window.addEventListener('load', function() {
    //this works.
    document.body.textContent = myproject.foo;
});

The above code still sets the body of the textContent to "bar" even when compiling. So what does @privateit really do?

+5
source share
2 answers

@private, @protected @public Closure, .

Compiler:

  • - jscomp_warning =

, Compiler:

  • - jscomp_error =

, , @private @protected, . , , JavaScript.

file1.js

goog.provide('ns1');

/**
 * Global private variable.
 * @private
 */
ns1.global = 'foo';
alert('ns1.global = ' + ns1.global); // OK in same file.


/** @constructor */
ns1.Constructor = function() {
  /** @private */
  this.secret_ = ns1.global;
};

ns1.instance = new ns1.Constructor();
alert(ns1.instance.secret_); // No warning in same file.

file2.js

goog.provide('ns2');

goog.require('ns1');

alert('ns1.global = ' + ns1.global); // Not allowed.

ns2.instance2 = new ns1.Constructor();
alert(ns2.instance2.secret_); // Not allowed.

--jscomp_error=visibility Closure .

ERROR - Access to private property global of ns1 not allowed here.
alert('ns1.global = ' + ns1.global);
                        ^
ERROR - Access to private property secret_ of ns1.Constructor not allowed here.
alert(ns2.instance2.secret_);
      ^

( ) JavaScript JavaScript .

+5

cpeisert , , : .

@private , , , , .

, , - , .

+1

All Articles