Javascriptのいくつかのモダンなhack技巧

12271 ワード

回転:http://berzniz.com/post/68001735765/javascript-hacks-for-hipsters
Javascript Hacks for Hpsters
Javascript is so much fun、except when it's not.
The’s always the fear of runtime errors that keeps s s s s s th inking all the time while writiting code.It makes s better coders-we have no other option than to visualize line of code as it.s.s.running weit.
That’s why it’s so importent to have tidy code.Small code.Pretty code.Code you just fall in love with.Other wise,Javascript will scare you away.
I gathered some fun snippets I enjoy using instead of boring code that tars too much space.Some makes the code share,cleaner and more readable.Other ar are just playin hacks for debuggg.
I learned all of this from open source code(until node.js all javascript code was open source,wasn't it),but I'll write them here is I inventted them.
Hpspter Hack〓1-Method caling
I really hate if/else blocks and this quite a useful trick to call the right function based on a bolean value.
// Boring

if (success) {

obj.start();

} else {

obj.stop();

}

 

// Hipster-fun

var method = (success ? 'start' : 'stop');

obj[method]();
 
 
view raw
jshipsptermethod.js hosted with❤ by 
GitHub
Hpspter Hack〓2-String jins
I t’s a known fact that stregs like other streings.Sooner or later you’d like to concatentate to to more of them.I don’t really+ing them together,so ジョン()coes to the recue.
['first', 'name'].join(' '); // = 'first name';

 

['milk', 'coffee', 'suger'].join(', '); // = 'milk, coffee, suger'
 
view raw
jshipspterジョイン.js hosted with❤ by 
GitHub
Hpspter Hack〓〓3-Default Operator𞓜
Javascript is all about not knowing what n object holds.Sometime You get it as a function argment,other times You might read it from the network or a configration file.Either way,you can use the fight the first the
// default to 'No name' when myName is empty (or null, or undefined)

var name = myName || 'No name';

 

 

// make sure we have an options object

var doStuff = function(options) {

  options = options || {};

  // ...

};
 
Hpspter Hack〓4-Gard Operator&&
Simiar to the Default Operator,this one is super useful.It eliminates almost all IF cals and makes for a nivercode.
// Boring

if (isThisAwesome) {

  alert('yes'); // it's not

}

 

// Awesome

isThisAwesome && alert('yes');

 

// Also cool for guarding your code

var aCoolFunction = undefined;

aCoolFunction && aCoolFunction(); // won't run nor crash
 
view raw
jshipspterand_and.js hosted with❤ by 
GitHub
Hpspter Hack〓5-XXX Operator
This one is totally copyrighted and also SFW.Whenever I write some code,but then have to consult the web,or a different part of the code,I add an xxx line to the code.This makes the code break so I can get back to the specific place and fix it later.Music ease to search for it(xxx usualy never appars)and you don’t have to think aboot to to to to to to to to to to to to compment.
var z = 15;

doSomeMath(z, 10);

xxx // Great placeholder. I'm the only one using xxx and it's so easy to find in code instead of TODOs

doSomeMoreMath(z, 15);
 
view raw
jshipspterxxx.js hosted with❤ by 
GitHub
Hpspter Hack〓〓6-Timing
Ever wonder what’s faster:Looping with an i++or looping with an i— ? Yeah、me neither.For those who does、you can use the consoline’s timing methods to test for s loops or any other evere blocking code.
var a = [1,2,3,4,5,6,7,8,9,10];

 

console.time('testing_forward');

for (var i = 0; i < a.length; i++);

console.timeEnd('testing_forward');

// output: testing_forward: 0.041ms

 

console.time('testing_backwards');

for (var i = a.length - 1; i >= 0; i--);

console.timeEnd('testing_backwards');

// output: testing_backwards: 0.030ms 
 
view raw
jshipsptertiming.js hosted with❤ by 
GitHub
Hpspter Hack菗7-Debugging
I learned this one from a Java developer.I have aboutelyのidea how he knew about it and I didn't,but I've been using it ever since.Just drop a デバッグゲージ statement and the debuggar will stop on that line.
var x = 1;

debugger; // Code execution stops here, happy debugging

x++;

 

 

var x = Math.random(2);

if (x > 0.5) {

  debugger; // Conditional breakpoint

}

x--;
 
view raw
jshipspterdebugger.js hosted with❤ by 
GitHub
Hpspter Hack〓8-Old School デバッグゲージ
I’ve always been a“printf debuggar”more than a line-by-line-i-n-debuggar kind of developer.If you’re like me,you’ll want to“export”some prvate vars to the global scope inder.order.order to extrom.ine.ine.ine.orders.ine.order。
var deeplyNestedFunction = function() {

  var private_object = {

    year: '2013'

  };

  

  // Globalize it for debugging:

  pub = private_object;

};

 

// Now from the console (Chrome dev tools, firefox tools, etc)

pub.year;
 
view raw
jshipspterglobals_for_デバッグgg.js hosted with❤ by 
GitHub
Hpspter Hack〓9-Ultra Light Templates
Aree you still concatentating stings using the+operator?Here’s a better way to combine a sentence with your data.It’s caled templating and here’s a mini frame ebook in 2.5 line of code.
var firstName = 'Tal';

var screenName = 'ketacode'

 

// Ugly

'Hi, my name is ' + firstName + ' and my twitter screen name is @' + screenName;

 

// Super

var template = 'Hi, my name is {first-name} and my twitter screen name is @{screen-name}';

var txt = template.replace('{first-name}', firstName)

                  .replace('{screen-name}', screenName);