问题描述:

I have a doubt about JS patterns and performance, after read "Javascript: The good parts" by Douglas Crockford you an idea of how Closures works, the first in mind it's to write code like this

(function(){

"use strict";

var OpenSloth = {};

OpenSloth.someFunction = function () {...};

OpenSloth.someOtherFunction = function () {...};

window.OpenSloth;

})();

But I read latter a book named "High Performance Javascript" by Nicholas C. Zakas (Also O'Reilly) and they say from the page 24 to 25:

Closures are one of the most powerful aspects of Javascript, allowing a function to access data outside of its local scope. The use of cloasures has been popularized through the writings of Douglas Crockford and is now ubiquitous in most complex web aplications. There is, however, a performance impact associated with using cloasures...

...Since the closure's [[Scope]] property cointains references to the

same objects as the execution context's scope chain, there is a side

effect. Typically, a function's activation object is destroyed when

the execution context is destroyed. When there's a cloasure involved,

through, the activation object isn't destroyed, because a reference

still exists in the closure's [[Scope]] property. This means that

cloasures require more memory overhead in a script than a nonclosure

function...

High Performance JavaScript, by Nicholas C/ Zakas. Copyright 2010 Yahoo!, Inc, 978-0-596-80279-0."

After that I want to reduce closures as far as I can, then I came up with this solution:

var OpenSloth = {};

OpenSloth._someFunction = function () {

"use strict";

...

};

OpenSloth._someOtherFunction = function () {

"use strict";

...

};

But I want to know whats the conventions about it, I'm writing bad code with this second option? and why? it is an anti-pattern?

Thanks for your time.

网友答案:

Well, closures gives you ability to write modular code, so you won't collide with the same variables in different places. You're using inside only those variables you want, and cannot access them for the outside. It's safer. In your second example for sure i would first check if object you want to use is not already used e.g. var OpenSloth = OpenSloth || {}; hope this helps

相关阅读:
Top