Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JavaScript

1,480 views

Published on

Некоторые фичи и интересности со встречи ДевКлаба 30.03.2010

Published in: Education
  • Be the first to comment

  • Be the first to like this

JavaScript

  1. 1. JavaScript <ul><li>Подзаголовок </li></ul>Александр Мочёнов
  2. 2. Вопросы <ul><li>Кто считает, что он знает JavaScript? </li></ul><ul><li>Кто считает, что JavaScript - какашко? </li></ul>1
  3. 3. Я не буду говорить о <ul><li>DOM </li></ul><ul><li>Истории JS и его будущем </li></ul><ul><li>Регулярных выражениях, Таймерах </li></ul><ul><li>Подробно о Массивах </li></ul><ul><li>Конвеншенах </li></ul><ul><li>И многом другом ... </li></ul>2
  4. 4. А лучше раскажу о <ul><li>О feature’а х </li></ul><ul><li>О том, о чём кто-то может не знать </li></ul><ul><li>О том почему JavaScript - клёвый </li></ul>3
  5. 5. Факты и мысли <ul><li>JavaScript - is NOT Java! </li></ul><ul><li>JavaScript has prototypal inheritance </li></ul><ul><li>Популярность </li></ul><ul><li>Один для веба </li></ul><ul><li>The amazing thing about JS is … </li></ul>4
  6. 6. Литералы var obj = {object: &quot;literal&quot; }; // === new Object(); var str = &quot;string literal&quot; ; // === new String(); var arr = [10, 20, 30]; // === new Array(); var num = 10; // === new Number(); var boo = true ; // === new Boolean(); var reg = /regexp literal/i ; // === new RegExp(); var fun = function (){ return true ;} // === new Function(); var dat = new Date(2010, 11, 30); // no literal Object() String() Number() Boolean() ... etc 5
  7. 7. Объекты cat [ &quot;do&quot; ]( &quot;eat&quot; ); //do - is reserved word assert( cat .status === &quot;eating&quot; ); cat [ &quot;do&quot; ]( &quot;clean_wc&quot; ); >>> Uncaught #<an Object> var cat = { actions:{ sleep: function (){ cat .status = &quot;sleeping&quot; ; }, eat: function (){ cat .status = &quot;eating&quot; ; }, clean_wc: function (){ cat .status = &quot;cleaning wc&quot; ; } }, loves: [ &quot;sleep&quot; , &quot;eat&quot; ], &quot;do&quot; : function ( action ){ if ( this .loves.has( action ) ){ this .actions[ action ](); } else { throw {name: &quot;Cat Exception&quot; , message: &quot;Br-r-r!&quot; }; } } }; 6
  8. 8. for ... in var budget = { beer : 1250, sandwich : 500, pizza: 670 }; var sum = 0; for (item in budget ){ if ( budget .hasOwnProperty(item)){ sum += budget [item]; } } assert( sum === 2420); 7
  9. 9. Функции обычные объекты <ul><li>function talk ( buddy ){ </li></ul><ul><li>return &quot;I talk with &quot; + buddy + &quot; for &quot; + </li></ul><ul><ul><ul><ul><ul><li>talk.long + &quot; minutes&quot; ; </li></ul></ul></ul></ul></ul><ul><li>}; </li></ul><ul><li>talk.long = 5; </li></ul><ul><li>assert(talk( &quot;John&quot; ) === &quot;I talk with John for 5 minutes&quot; ); </li></ul>8
  10. 10. Функции - создание var twiceTen = getTwice(10); //Can use it before declaration // - Function as Expression function getTwice ( value ){ return value * 2; }; assert( twiceTen === 20); // - Function as statement var pub = function priv ( param ){ //param, and priv are visible only here. }; pub(111); //Can use it after declaration. 9
  11. 11. Анонимная функц. var callme = function ( func ){ return func(); //calling passed function }; var res = callme( function (){ //I am anonymous function return &quot;Thank you&quot; ; }); assert( res == &quot;Thank you&quot; ); 10
  12. 12. arguments var argArr = function ( args ){ return Array.prototype.slice.apply( args ); }; var argSum = function (){ var sum = 0; var argArray = argArr(arguments); argArray .push(5); for ( var i = 0; i < argArray .length; i ++){ sum += argArray [ i ]; } return sum ; }; assert(argSum(1,2,3,4) === 15); 11
  13. 13. Вызов функции простой и метод function simpleFunction (){ //this => global object return &quot;simple value&quot; ; }; assert(simpleFunction() === &quot;simple value&quot; ); var obj = { value: &quot;simple value&quot; , method: function (){ //this => parent object return this .value; } }; assert( obj .method() === &quot;simple value&quot; ); 12
  14. 14. Вызов функции псевдо-конструктор var juice = function ( type ){ return { make: function (){ //this - parent object this .ready = true ; }, drink: function (){ if ( this .ready){ return &quot;Drinking &quot; + type + &quot; juice!&quot; ; } } }; }; var juice1 = juice( &quot;pineapple&quot; ); juice1 .make(); assert( juice1 .drink() === &quot;Drinking pineapple juice!&quot; ); 13
  15. 15. Вызов функции конструктор var Jazz = function ( artist ){ //this - is newly created object (if &quot;new&quot; was used) this .music = &quot;on&quot; ; this .play = function (){ if ( this .music === &quot;on&quot; ){ return artist + &quot; is playing&quot; ; } } return undefined ; //for demo only }; var jazz = new Jazz ( &quot;Louis Armstrong&quot; ); assert( jazz .play() === &quot;Louis Armstrong is playing&quot; ); 14
  16. 16. Вызов функции <ul><li>var DeathStar = function (){ </li></ul><ul><li>this .enemy = &quot;Rebel Alliance&quot; ; </li></ul><ul><li>this .shoot = function (){ </li></ul><ul><li>return &quot;Shoot &quot; + this .enemy + &quot; with superlaser&quot; ; </li></ul><ul><li>}; </li></ul><ul><li>}; </li></ul><ul><li>var deathStar = new DeathStar (); </li></ul><ul><li>assert( deathStar .shoot() === </li></ul><ul><ul><ul><ul><li>&quot;Shoot Rebel Alliance with superlaser&quot; ); </li></ul></ul></ul></ul><ul><li>//!!! Rebels captured the Death Star ... </li></ul><ul><li>assert( </li></ul><ul><ul><li>deathStar .shoot.apply({enemy: &quot;Dark Side&quot; }) === </li></ul></ul><ul><ul><li>&quot;Shoot Dark Side with superlaser&quot; </li></ul></ul><ul><li>); </li></ul>15
  17. 17. Scope //No C style block scopes var outside = 10; for (;;){ var inside = 10; break ; } assert( outside === inside ); //Global Scope is Bad, but necessary 16
  18. 18. Scope var globalVar = 10; function one (){ var innerVar = 10; function two (){ var innerInnerVar = 10; noVarVar = 10; assert( globalVar === innerVar && innerVar === innerInnerVar ); } assert( globalVar === innerVar ); //innerInnerVar - not in this scope two(); } one(); //Only global variables is in this scope assert( globalVar === noVarVar); 17
  19. 19. (function(){})(); var letters = [ &quot;D&quot; , &quot;E&quot; , &quot;V&quot; , &quot;C&quot; , &quot;L&quot; , &quot;U&quot; , &quot;B&quot; ]; var sayArr = []; for ( var i = 0; i < letters .length; i ++){ sayArr .push( function (){ return &quot;Say &quot; + letter[ i ] + &quot;!&quot; ; }); } for ( var j = 0; j < sayArr .length; j ++){ console.log( sayArr [ j ]()); } //Say undefined! //Say undefined! //Say undefined! //... 18
  20. 20. (function(){})(); var letters = [ &quot;D&quot; , &quot;E&quot; , &quot;V&quot; , &quot;C&quot; , &quot;L&quot; , &quot;U&quot; , &quot;B&quot; ]; var sayArr = []; for ( var i = 0; i < letters .length; i ++){ sayArr .push( function (){ return &quot;Say &quot; + i + &quot;!&quot; ; }); } for ( var j = 0; j < sayArr .length; j ++){ console.log( sayArr [ j ]()); } //Say 7 //Say 7 //Say 7 //... 19
  21. 21. (function(){})(); var letters = [ &quot;D&quot; , &quot;E&quot; , &quot;V&quot; , &quot;C&quot; , &quot;L&quot; , &quot;U&quot; , &quot;B&quot; ]; var sayArr = []; for ( var i = 0; i < letters .length; i ++){ ( function ( k ){ sayArr .push( function (){ return &quot;Say &quot;&quot; + letters [ k ] + &quot;&quot; !&quot; ; }); })( i ); } for ( var j = 0; j < sayArr .length; j ++){ console.log( sayArr [ j ]()); } //Say &quot;D&quot; ! //Say &quot;E&quot; ! //Say &quot;V&quot; ! //... 20
  22. 22. (function(){})(); 22 var letters = [ &quot;D&quot; , &quot;E&quot; , &quot;V&quot; , &quot;C&quot; , &quot;L&quot; , &quot;U&quot; , &quot;B&quot; ]; var sayArr = []; for ( var i = 0; i < letters .length; i ++){ sayArr .push( ( function ( i ){ return &quot;Say &quot;&quot; + letters [ i ] + &quot;&quot; !&quot; ; })( i ) ); } for ( var j = 0; j < sayArr .length; j ++){ console.log( sayArr [ j ]()); }
  23. 23. (function(){})(); var yourLib = ( function (){ var i = 10; var b = 20; //your scoped code here function innerLib ( c ){ return c + i + b ; }; return innerLib; })(); //i, b not visible here assert(yourLib(30) === 60); 23
  24. 24. Closure I’m gonna build my own amusement park. With ... var RudeRobot = function (){ var beerCans = 0; //Private variable this .drinkBeer = function (){ beerCans ++; return this ; }; }; var bender = new RudeRobot (); bender .drinkBeer().drinkBeer(); //Can't find out how many beers Bender drunk 24
  25. 25. Closure - guess number <ul><li>function makeGame (){ </li></ul><ul><li>var theNumber = Math.round(Math.random() * 10); </li></ul><ul><li>var numberOfGuesses = 0; </li></ul><ul><li>return function ( guess ){ </li></ul><ul><li>numberOfGuesses ++; </li></ul><ul><li>if ( guess == theNumber ){ </li></ul><ul><li>return &quot;You did it in &quot; + numberOfGuesses + &quot; tries&quot; ; </li></ul><ul><li>} else { </li></ul><ul><li>return &quot;No. My number is &quot; + </li></ul><ul><ul><ul><ul><ul><li>( guess < theNumber ? &quot;bigger&quot; : &quot;smaller&quot; ); </li></ul></ul></ul></ul></ul><ul><li>} </li></ul><ul><li>}; </li></ul><ul><li>}; </li></ul><ul><li>var tryToGuess = makeGame(); </li></ul><ul><li>tryToGuess(3); // --> No. My number is bigger </li></ul><ul><li>tryToGuess(7); // --> No. My number is smaller </li></ul><ul><li>tryToGuess(5); // --> You did it in 3 tries </li></ul>25
  26. 26. Closure - fibonacci var count = 0; var fibonacci = function fib ( n ){ count ++; return n < 2 ? n : fib( n - 1) + fib( n - 2); }; for ( var i = 0; i <= 10; i += 1){ console.log( i + &quot; -> &quot; + fibonacci( i )); } assert( count === 453); //453 calls 26
  27. 27. Closure - fibonacci var count = 0; var fibonacci = ( function (){ var memo = [0, 1]; var fib = function ( n ){ count ++; var result = memo [ n ]; if ( typeof result !== 'number' ){ result = fib( n - 1) + fib( n - 2); memo [ n ] = result ; } return result ; }; return fib ; })(); for ( var i = 0; i <= 10; i ++){ console.log( i + &quot; -> &quot; + fibonacci( i )); } assert( count === 29); 27
  28. 28. Curry - friends function friends ( boy , girl ){ return boy + &quot; and &quot; + girl + &quot; are friends.&quot; ; } var boysFriends = function (){ var thatArgs = argArr(arguments); return function (){ var thisArgs = argArr(arguments); return friends.apply( null , thatArgs .concat( thisArgs )); }; }; var johnsFriends = boysFriends( &quot;John&quot; ); assert(johnsFriends( &quot;Jully&quot; ) === &quot;John and Jully are friends.&quot; ); assert(johnsFriends( &quot;Marta&quot; ) === &quot;John and Marta are friends.&quot; ); 28
  29. 29. Наследование <ul><li>Наследование от объекта к объекту </li></ul><ul><li>Prototype - ссылка на родителя </li></ul><ul><li>Всё идёт от Object </li></ul>29
  30. 30. Prototype <ul><li>function Monkey (){}; </li></ul><ul><li>var codeMonkey = new Monkey(); </li></ul><ul><li>Monkey.prototype.code = function (){ return &quot;Code, code!&quot; ; }; </li></ul><ul><li>assert( codeMonkey .code() === &quot;Code, code!&quot; ); </li></ul><ul><li>function Vasja (){}; </li></ul><ul><li>Vasja.prototype = new Monkey(); </li></ul><ul><li>var progerVasja = new Vasja(); </li></ul><ul><li>Vasja.prototype.decide = function (){ </li></ul><ul><ul><li>return &quot;Shut-up lemons, I know what to do!&quot; ; }; </li></ul></ul><ul><li>assert( progerVasja .decide() === &quot;Shut-up lemons, I know what to do!&quot; ); </li></ul><ul><li>assert( progerVasja .code() === &quot;Code, code!&quot; ); </li></ul>30
  31. 31. Наследование <ul><li>Прототипное наследование </li></ul><ul><li>Классическое, типа Классы и всё такое </li></ul><ul><li>Функциональное </li></ul><ul><li>Подробнее расскажет Вася. </li></ul>31
  32. 32. Дополнения к примитивам Array.prototype.map = function ( fn ){ for ( var i = 0, size = this .length; i < size ; i ++){ this [ i ] = fn .call( this [ i ], i , this ); } return this ; }; var arr = [1,2,3,4].map( function ( i , array ){ if ( this % 2 == 0){ return this * 3; } return this ; }); assert( arr == &quot;1,6,3,12&quot; ); // == using for casting 32
  33. 33. Кэширование метода Function.prototype.cached = function (){ var _cache = {}; var fun = this ; return function (){ var args = argArr(arguments); var result = _cache [ args ]; if (! result ){ result = fun .apply( null , args ); _cache [ args ] = result ; } return result ; }; }; 33
  34. 34. Кэширование метода Function.prototype.cached = function (){ ... var count = 0; var fibo = function ( n ){ count ++; return n < 2 ? n : fibo( n - 1) + fibo( n - 2); }.cached(); for ( var i = 0; i <= 10; i += 1){ console.log( i + &quot; -> &quot; + fibo( i )); } assert( count === 12); 34
  35. 35. Вкусненькое scope var var APP = { constants: { MAX_BUK: 10, MIN_BUK: 20 }, messages: { hello_world: &quot;Hello World&quot; , cancel: &quot;Cancel&quot; }, sayHello: function (){ return this .messages.hello_world; } }; 35
  36. 36. Вкусненькое использование && и || в выр а жениях var action = function (){ return work && work .doing && work .doing() || &quot;stay home&quot; ; }; assert(action() === &quot;stay home&quot; ); var work = { doing: function (){ return &quot;hard working&quot; ; } }; assert(action() === &quot;hard working&quot; ); 36
  37. 37. Вкусненькое falsy values if (0 || NaN || '' || false || null || undefined ){ //All those values are falsy assert( false ); } else { //All other are truthy assert( true ); } 37
  38. 38. Вкусненькое evil twins == и === assertFalse( '' == '0' ); //false assertTrue( 0 == '' ); //true assertTrue( 0 == '0' ); //true assertFalse( false == 'false' ); //false assertTrue( false == 0); //true assertFalse( false == undefined ); //false assertFalse( false == null ); //false assertTrue( null == undefined ); //true assertTrue( ' ' == 0); //true 38
  39. 39. Вкусненькое evil twins assertFalse( '' === '0' ); assertFalse( 0 === '' ); assertFalse( 0 === '0' ); assertFalse( false === 'false' ); assertFalse( false === 0); assertFalse( false === undefined ); assertFalse( false === null ); assertFalse( null === undefined ); assertFalse( ' ' === 0); 39
  40. 40. Вкусненькое null, parseInt, IEEE 754, NaN //null var nullable = null ; assert( typeof nullable === 'object' ); assert(nullable === null ); //pasreInt assert(parseInt( &quot;08&quot; ) === 0); //Octal assert(parseInt( &quot;08&quot; , 10) === 8); //Decimal //IEEE 754 assert(0.1 + 0.2 !== 0.3); //NaN var notANum = NaN; assert( typeof notANum === 'number' ); assert( notANum !== notANum ); assert(isNaN( notANum )); 40
  41. 41. Вкусненькое brackets style function iLikeCStyleBrackets () { return { word: &quot;boo-gaga&quot; } } var s = iLikeCStyleBrackets(); //assert(s.word === &quot;boo-gaga&quot;); //Makes error assert( s === undefined ); 41
  42. 42. Вкусненькое brackets style function iLikeCStyleBrackets () { return ; { word: &quot;boo-gaga&quot; }; }; 42
  43. 43. Вкусненькое brackets style function iUseGoodBrackets (){ return { word: &quot;good boy&quot; }; }; var s = iUseGoodBrackets(); assert( s .word === &quot;good boy&quot; ); 43
  44. 44. Книги JavaScript: The Good Parts JavaScript Ninja JavaScript: The Definitive Guide Douglas Crockford John Resig David Flanagan
  45. 45. JavaScript – это клёва!
  46. 46. Спасибо! Александр Мочёнов [email_address]

×