What does the #private annotation actually do in Google Closure JavaScript code? - javascript

When I put a comment above my variable or function with #private in it what is it actually doing? I have looked at the documentation but I'm still not sure.
goog.provide('myproject');
/** #private */
myproject.foo = "bar";
I can still access it when I open up chrome's development tools (myproject.foo). And...
goog.require('myproject');
window.addEventListener('load', function() {
//this works.
document.body.textContent = myproject.foo;
});
The above code still set's the bodies textContent to equal "bar", even when compiled. So what does #private actually do?

The access control annotations #private, #protected, and #public are
directives for the Closure Compiler that help developers enforce the
desired level of visibility for properties and functions.
To emit warnings for access violations use the Compiler flag:
--jscomp_warning=visibility
To emit errors for access violations use the Compiler flag:
--jscomp_error=visibility
Access control annotations are enforced on a per file basis,
meaning that any properties annotated #private or #protected may be
accessed anywhere within the same file. Also note that the compiler removes
these annotations from the compiled code since they are not part of the
JavaScript language.
Example
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.
With the flag --jscomp_error=visibility set, Closure Compiler emits the
following errors.
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_);
^
See Visibility (private and protected fields) in the Google JavaScript
Style Guide.

cpeisert implied this in his answer, but just to be explicit: these visibility annotations don't modify your output at all.
Marking a function as #private does not hide it or make it any less accessible in the resulting code than the Compiler normally would, and any third-party code that you introduce at runtime will be able to invoke such functions.
The only access protection offered by these annotations is against code that you compile in with them.

Related

JSDoc for function parameter properties + WebStorm

What is the correct JSDdoc declaration for company being a String in the code below?
fetch('https://api.github.com/users/mdo').then(res => res.json()).then(res => {
console.log(res.company);
});
I use WebStorm and it understandably underscores company as an Unresolved variable:
if I add
/** #namespace bogus.company **/
anywhere in the file, WebStorm is happy, but that doesn't make sense:
Is this a bug in WebStorm, or am I missing something about how JSDoc declarations are supposed to work?
Is JSDoc even supposed to be used for this use case?
If you check the inspection for unresolved javascript variable there is a Report undeclared properties as error option that you could uncheck.
I like to do something like this:
/**
* #param {Object} res
* #property {String} company
*/
function myOutput(res) {
console.log(res.company);
}
fetch('https://api.github.com/users/mdo')
.then(myToJson)
.then(myOutput);
But for small anonymous functions I wouldn't even bother. It's a weak warning so turn the inspection off or learn to live with it, I'd say. It's possible to cram in /** #param {*} something */ in anonymous functions as well, but often it only serves to reduce readability.
Another option is to make a dummy file soomething.js somewhere under your content-root with an anonymous function like:
(() => {
return {
"github-users-response" : {
"company" : "sample"
}
}
});
And now webstorm will figure that company actually is defined in your other files. You can even put it in a different content-root if you want to keep it separate from your project.

Prevent Closure Compiler from renaming properties without using bracket notation

I'm working on a product which needs to conditionally expose an API to the end user. We're using the Closure Compiler for minification. The part of the API that I'm trying to expose is a function that calls a callback with a Result whose value is an object with certain properties.
Specifically, the function I'm trying to expose looks like this (in pseudo-jsdoc notation):
/**
* #type DocumentRenderResult {status: String, image?: HTMLImageElement|HTMLCanvasElement}
* #param {function(Result<DocumentRenderResult>)} callback
**/
function renderDocument (url, page, callback) {
}
And the Result class looks like this:
/**
* #template T
* #param {Boolean} ok
* #param {T} val
* #param {Error} err
**/
function Result (ok, val, err) {
this.ok = ok;
this.val = val;
this.err = err;
}
What I'd like is to expose both the Result object API - that is, the fact that there are ok, val, and err properties, and expose the renderDocument interface so that users providing a callback will be able to access the status and image properties.
One solution (possibly) is to use bracket notation everywhere, but since this is supposed to be only conditionally exposed (for certain end users), I'd like to separate the concept of whether it's minified or not from the code.
I think some combination of #implements and #export and an externs file can accomplish this, but I haven't figured it out.
Is what I'm trying to do possible?
There are 2 primary ways to handle this situation:
Without Closure-Library
Store all of your exports in a separate file that becomes the main entry point for the api exposed library. This methodology has no dependencies on external libraries. For an example of this, see my GeolocationMarker library.
With Closure-Library (or at least a part of it)
If you are willing to utilize a very small part of closure-library code in your project, you can use the #export annotation. #export annotations do nothing unless the compilation flag --generate_exports is specified.
When --generate_exports is used, the compiler will add the appropriate call to either closure-library's goog.exportProperty or goog.exportSymbol method.
/** #const */
var mynamespace = {};
/** #export */
mynamespace.maybeExposedMethod = function() {};
With the --generate_exports flag, the compiler will generate the code:
var mynamespace = {maybeExposedMethod:function() {}};
goog.exportSymbol("mynamespace.maybeExposedMethod",
mynamespace.maybeExposedMethod);
Instead of having to depend on all of closure-library. You can copy the definition for those 2 methods into your source. All that's needed is that they exist as those names.
Conditionally Renaming Record Types
Functions which return anonymous objects must be treated differently to prevent renaming. The best option here would be to define a record type in its own file. For the public api to block renaming, include the record definition as an extern. When you want the record properties to be renamed, include the definition as source.
my_typedefs.js
/** #typedef {{image: string, status: number}} */
var my_record_type;
my_method_def.js
/** #return {my_record_type} */
function my_method() {
return {
image: 'some_image.jpg',
status: 200
};
}
If my_typedefs.js is included in the compilation with the --js flag, the record properties will be renamed, but if it is included with the --externs flag, they will not be renamed.

Javascript Module Pattern and Google Closure Compiler

I am using the Google Closure Compiler on a Drupal project right now. My Javascript is structured using the Javascript Module Pattern.
Because of the way Drupal works, I am compiling each JS file individually. Simple Compilation mode works well, but I would like to use Advanced Compilation on each file.
My files are all variations on
var FOO = (function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
My problem is that Drupal.behaviors is a specific object in Drupal, and the attach property also is a specific property. When a Drupal page renders, Drupal.behaviors gets looped through, and all of the attach functions are called with the proper arguments. In other words, I don't want anything renamed with the Drupal object.
When I use Advanced Compilation mode, I get
var c = function(a, d, b) {
b.b.FOO = {a:function() {
do_stuff()
}};
return a
}(c || {}, jQuery, Drupal);
I have tried many variations on trying to get the compiler to recognize the whole Drupal object as an extern without luck. No matter what I try, .behaviors and .attach always get renamed.
Is there a way to tell the compiler to keep its hands off an entire object?
There is no concept "Don't modify any properties on this object". You can however setup an extern such as:
/** #interface */
function DrupalBehavior() {}
DrupalBehavior.prototype.attach = function(){};
/** #constructor */
function DrupalObject () {}
/** #type {Object.<string, DrupalBehavior>} */
DrupalObject.prototype.behaviors = {};
Then, in your code:
var FOO = (
/**
* #param {Object} me
* #param {jQuery} $
* #param {DrupalObject} Drupal
* #param {*=} undefined
*/
function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
In this case the Drupal argument will be renamed, but the behaviors property and its associated attach sub-property will not be.
One note on jQuery: You are passing the jQuery namespace object into the function as a
parameter. Closure-compiler does not trace the type well in this object. The annotation I have listed would be for an instace of the jQuery object as opposed to the entire jQuery namespace. This is probably not what you intended. The only type-safe way to handle this in Closure-compiler is NOT to pass namespaces through function closure.
Update: After looking through the JavaScript Module Pattern post you linked, they encourage passing global namespace objects into function closures. This pattern has known problems with Closure-compiler. You will need to choose to either follow the pattern in this regard or opt for full compatibility with ADVANCED_OPTIMIZATIONS.

requirejs exports doesn't work in firefox 15

I use a external library that uses requirejs I don't know
how its work but FileError is in the global scope in other browser
or in FF8 but in FF 14/15 says FileError not defined.
define(function (require, exports, module) {
"use strict";
var Async = require("utils/Async");
var NativeFileSystem = {
/**
* LOT OF CODE HERE
* ...
* ...
* ...
*/
/** class: FileError
*
* Implementation of HTML file API error code return class. Note that we don't
* actually define the error codes here--we rely on the browser's built-in FileError
* class's constants. In other words, external clients of this API should always
* use FileError.<constant-name>, not NativeFileSystem.FileError.<constant-name>.
*
* #constructor
* #param {number} code The error code to return with this FileError. Must be
* one of the codes defined in the FileError class.
*/
NativeFileSystem.FileError = function (code) {
this.code = code || 0;
};
/**
*THIS FIX THE PROBLEM BUT IT A HACK
*window.FileError = NativeFileSystem.FileError;
*/
// Define public API
exports.NativeFileSystem = NativeFileSystem;
});
Of course if I add window.FileError = NativeFileSystem.FileError; after the
function definition its work fine. But I don't want hack the library
The full source of the file is here
Brackets relies on the FileError class only for the error code constants.
The FileAPI is still a draft spec http://www.w3.org/TR/FileAPI/ and it appears they have changed FileError to DOMError in the time since we originally wrote NativeFileSystem. We could remove this dependency and define our own equivalent FileError constants to remove the dependency. We were attempting to model our API after the FileAPI, but it's been a moving target.

What is the best way to export library method, when using Closure Compiler?

Closure Compiler documentation clearly states: "Don't use Externs instead of Exports". Because Externs are very handy to use, I came down with a problem:
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
When using Closure Compiler with ADVANCED_OPTIMIZATIONS, function invoke is removed from the source. This could be prevented in two ways:
Adding the line after prototype definition:
Lib.prototype['invoke'] = Lib.prototype.invoke;
But this adds an ugly peace of code at the end of the output code:
Lib.prototype.invoke = Lib.prototype.g;
I managed to get rid of this by adding this line to the constructor:
this.invoke = this.invoke;
And this line to the externs file:
/**
* #param {String} str
*/
Lib.prototype.invoke = function(str){};
This way, Closure Compiler can't remove invoke function from the output code, because it is assigned by itself in the constructor, and also, it can't rename it, because it is defined in the externs file.
So witch method is better?
If you use JSDoc consistently, you could use the #export tag:
/**
* #param {String} str
* #export
*/
Lib.prototype.invoke = function(str){
//this function is called from outside to invoke some of Lib's events
};
and call the compiler with the --generate_exports flag.
This requires you to either include base.js from the Google Closure library, or to copy goog.exportSymbol and goog.exportProperty to your codebase.
Personally, I like defining interfaces in externs file and having my internal classes implement them.
// Externs
/** #interface */
function IInvoke {};
IInvoke.prototype.invoke;
/**
* #constructor
* #implements {IInvoke}
*/
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
You still export the constructor itself, but not the interface methods.

Categories