JS (JavaScript) 에 대하 여

28054 단어 javascript 전단
주류 브 라 우 저의 커 널
IE:trident
Chrome:webkit/blink
firefox:Gecko
Opera:presto
Safari:webkit

JS 도입 방식
      (  head  body )
    (    )

JS 기본 문법
  :
    :  ,    。  var。 (var a=100)
    :          ,*,$  *
           ,,$,  
          ,        


   (    ):
        (   ):Number,Boolean,String,undefined,null
              (    )
   (   ):array,Object,function,..data,RegExp


typeof()       (  number,string,boolean,object,undefined,function)
    :      :Number(mix)          NaN
                   parseInt(string,radix) string radix        10  
                   parseFloat(string)
                   num.toString(radix) num  radix  
                   String(mix)
                   Boolean()
           :isNaN()    number,  NaN  
                   ++/-- +/-(  )      
                   +      
                   - * / %         '1'*1=1
                   && || !
                   < > <= >=         ,       。         ,  ascii 
                   == !=        
       :===,!==


       :
           (   ,for  ,if  ...)
js    (    ,    )         ,       js   
       ,'=+/-'      

     :
'+':    ,     。
                    
'-','*','/','%','=','()':'()'     ,'='     
 '++','--','+=','-=','/=','*=','%='
e.g. var a = 10 ; var b = ++a - 1 + a++ (  b  21,a  12)
 var a = 1 ; var b = a-- + --a (  b  0(  --a,  b=0+0=0),a  -1) 

     :'>','=','<=','!='(     boolean ) NaN!=NaN

     :'&&'(     ),'||'(     ),'!'(         )
e.g. var a = 1 && 2+2 (a 4)
    var a = 0 && 2+2 (a 0)
    var a = 2+1 && 0 (a 0)
    var a = 1 || 3 (a 1)
    var a = 0 || 2 (a 2)
    (window.foo || (window.foo='bar')) (window.foo   bar(     ))

    false  :undefined,null,NaN,'',0,false

    :if,if else if,switch case,break,continue
    :for,while,do while


함수.
  :    (function xxx(){})
     (       :var test=function xxx(){},        (  ):var test=function (){})
    :    (       theFirstName)
           :  (      :   .length),  (arguments        ,      :arguments.length)
            


e.g.1  5   (  )
    function mul(n){
        if(n==1 || n==0)
        {
            return 1
        }
        return n*mul(n-1);
    }
    mul(5);




역할 영역
     :          (            )
        :             (          ,          )
      ,           GO  
      ,            AO  ,  0    AO,1    GO


           ,          :
 e.g. function a(){
        function b(){
          function c(){
          }
          c();
        }
      b();
    }
    a();

   a defined  a.[[scope]] --> 0:GO
   a doing  a.[[scope]] --> 0:aAO 1:GO
   b defined  b.[[scope]] --> 0:aAO 1:GO
   b doing  b.[[scope]] --> 0:bAO 1:aAO 2:GO 
   c defined  c.[[scope]] --> 0:bAO 1:aAO 2:GO
   c doing  c.[[scope]] --> 0:cAO 1:bAO 2:aAO 3:GO
   
   with       :with(     ){     } 
                                   ,                。
   e.g.
   var obj={name:'obj'};
   function test(){
        var age=123;
        var name='scope';
        with(obj){
               console.log(name);  //  obj
               console.log(age);  //  123
        }
   }       

JS 3 부작 (프 리 컴 파일 포인트)
    
   (           )
    


   :        
              
     :imply global      :     ,           ,        (window)  (var a=b=123(b       , window  。  window.a undefined,window.b 123))
                ,  window   (var a=123 => window.a=123)
        :  AO  
                     ,         AO   ,  undefined
                      
                        ,      

e.g. function fn(a){                 1.  AO  (      )
    console.log(a);               2.        
    var a=123;                      AO{a:undefined,b:undefined}
    console.log(a);               3.        
    function a(){};                 AO{a:1,b:undefined}
    console.log(a);               4.      
    var b=function(){}              AO{a:function a(){},b:undefined,d:function d(){}}
    console.log(b);
    function d(){}
    }
    fn(1)

     console.log(a)    function a(){}
     var a=123,    AO{a:123,b:undefined,d:function d(){}}
   console.log(a)    123
      function a(){}(          )
   console.log(a)    123
    var b=function (){},    AO{a:123,b:function (){},d:function d(){}}
   console.log(b)    function (){}

            ,       GO  (window) 

e.g.1 console.log(test);
   function test(test){
    console.log(test);
    var test=234;
    console.log(test);
    function test(){};
   }
   test(1);
   var test=123;

      GO  :GO{test:function (){...}}
      AO  :AO{test:function (){}}

        console.log(test) function(){}
       function(){}
     var test=234,  AO{test:234}
       234

   e.g.2 global=100;
         function fn(){
         console.log(global);
         global=200;
         console.log(global);
         var global=300;
         }
         fn();
         var global;

            GO:{global:100}
            AO:{global:undefined}
                 undefined(AO      AO  )
            global=200;  AO:{global:200}
                 200

  e.g.3 function test(){
            console.log(b);
            if(a){
                var b=100;
                }
                console.log(b);
                c=234;
                console.log(c);
                }
                var a;
                test();
                a=10;
                console.log(c);

                   GO:{a:undefined}
                   AO:{b:undefined}
                      undefined
                  a undefined,    var b=100
                        undefined
                  c=234,AO   c,    c   GO ,  GO{a:undefined,c:234}
                      234
                   a=10,  GO{a:10,c:234}
                      234

 e.g.4 var x=1;
       if(function f(){}){
          x+=typeof f;
       }
       console.log(x);

         (function f(){})    ,  f undefined
         x   1undefined
       (         typeof     , undefined)


     GO AO  , AO       ,   GO  
                
   GO AO           


즉시 실행 함수
                  (       )
(function (  (    )){}(  (    )))
              
 :var test=function (){}();
    +function test(){}();
    (function test(){})();

폐쇄 (중점)
     :              
     :                   ,        ,           
     :      (     )
                (    )
                 ,     
                ,        
            

e.g.  4 li      
    var li=document.getElementByTagName('li');
     for(var i=0;i

대상
    , , , :
 :   .   =   
 :delete    .       
 :   .       =     
 :   .       

       :
1.      /      var obj={}
2.     (       : TheFirstName):         Object():var obj=new Object()
                                                :function    (){this.   =   ...}
                                                    var    = new    ()
3. var obj=Object.create(  /null)(             )

         :1.            this={}(AO:{this:{xxx}})
                   2.  this.xxx=xxx
                   3.     this(               ,    ,    this)
 
    :new String()
         new Boolean()
         new Number()
 e.g. var str='abc';
      str+=1;
      var test=typeof(str);
      if(test.length==6){
            test.sign='typeof        String';
            (             ,      )
            //new String(test).sign='xxx'   delete
       }
       //new String(test).sign( undefined)
       cosnole.log(test.sign);
              undefined
  

원형
   function       ,                    
            ,             
      
             
      :    __proto__  (   .prototype)
           :constructor
          :   .hasOwnProperty(   )

e.g. Person.prototype.name='sunny'
     function Preson(){}
     var person=new Preson();
     Preson.prototype.name='cherry';
        person.name='cherry'
     
     Person.prototype.name='sunny'
     function Preson(){}
     var person=new Preson();
     Preson.prototype.name={name:'cherry'}
        
     var obj={name:'a'};
     var obj1=obj;
     obj={name:'b'};(     )
          person.name    'sunny'(   __proto__       Person.prototype)

                 Object.prototype

undefined null    

  this  :call,apply
call:      .call(this       ,  )
apply:      .apply(this       ,[  ])

call apply   :        
                   call               
                   apply    arguments


계승 모드
1.     (   ):           
2.       :             
                              
3.     :           
4.     
        :
   function inherit(Target,Origin){
        function F(){};
        F.prototype=Origin.prototype;
        Target.prototype=F.prototype;
        Target.prototype.constructor=Target;
        Target.prototype.uber=Origin.prototype;
    }
        :
   var inherit=(function (){
        var F=function (){};
        return function(Target,Origin){
             F.prototype=Origin.prototype;
             Target.prototype=F.prototype;
             Target.prototype.constructor=Target;
             Target.prototype.uber=Origin.prototype;
        }
   }())
     

네 임 스페이스
    ,      ,        

               ,        
var name='bcd';
var init=(function (){
    var name='abc';
    function callName(){
        console.log(name);
    }
    return function(){
        callName();
    }
}())
init();
       name  abc

    Webpack 
  

JS 체인 호출 모드 구현 (JQ 모방)
 :obj.eat().smoke().drink()

       return this

대상 매 거
    :for      

    :for in  
for(var xxx(   ) in    ){console.log(   [xxx])}

배열, 대상 을 구분 하 는 세 가지 방법
   :instanceof
  A     B         (  A          B   ):A instanceof B
  :[] instanceof Array --> true 
  :{} instanceof Object --> true

   :constructor
  :obj={},obj.constructor --> function Object()
  :arr=[],arr.constructor --> function Array()

   :toString()
  :Object.prototype.toString.call([]) --> [object Array]
  :Object.prototype.toString.call([]) --> [object Object]

this 에 대하 여
        this -> window
       this -> window
call/apply           
obj.func();   func()   this  obj(   this   )

e.g.1 var name='222';
     var a={
        name:'111',
        say:function(){
            console.log(this.name);
         }
      }
      var fun=a.say;
      fun();  //    
      a.say(); //a  
      var b={
          name:'333',
          say:function(fun){
                fun();
          }
       }
       b.say(a.say);  //     this  ,   a.say         (          b    ),        
       b.say=a.say;
       b.say();  //   b  
       
               :222,111,222,333
  
 e.g.2 var foo=123;
        function print(){
            this.foo=234;
            console.log(foo);
        }
        print();
        
          this.foo=234 ,  this  window,  GO foo   234
               234
        
       print()  new print():     this=Object.create(print.prototype),this   window 
           123
  
  e.g.3 var a=5;
        function test(){
            a=0;
            alert(a);
            alert(this.a);
            var a;
            alert(a);
        }
        test();      0 5 0
        new test();     0 undefined(this    a) 0
        
  e.g.4 var bar={a:'002'};
        function print(){
            bar.a='a';
            Object.prototype.b='b';
            return function inner(){
            console.log(bar.a);
            console.log(bar.b);
            }
        }
        print()();(          ,       )       a,b
        
       
arguments.callee:        。                    。        ,              (   “    ”),      。
e.g. var num=(function(n){
        if(n==1){
            return 1
         }
         return n * arguments.callee(n-1)
     }(100))
                    
 func.caller:           
 
   :arguments.callee func.caller           
 

클론
                :
        :       ,             ,       ,   ,   
        :                   ,    。                    
    
        :
    function clone(origin,target){
        var target=target || {};
        for(var prop in origin){
            target[prop]=origin[prop];
          }
          return target;
     }

        :
        :
    1.          (typeof)
    2.          (instanceof,toString(    ),constructor)
    3.           
    4.   
    function deepClone(origin,target){
            var target=target || {};
            var toStr=Object.prototype.toString;
            var arrStr="[object Array]";
            for(var prop in origin){
                   if(origin.hasOwnProperty(prop)){  //        
                        if(origin[prop] !== "null" && typeof(origin[prop])=='object'){
                             if(toStr.call(origin[prop])==arrStr){ //          
                                 target[prop]=[];  //      
                             }
                             else{  //         
                                 target[prop]={};   //      
                             }
                            deepClone(origin[prop],target[prop]) 
                        }
                        else{  //       
                            target[prop]=origin[prop];
                        } 
             }    
        }
      

배열 과 클래스 배열
       :
var arr=[];
var arr=new Array(1,2,3,4);
var arr=new Array(10);  
new Array():      n          n     
                           
  
       :
 arr[n]: ,       ,      undefined
 arr[n]=xxx: ,     
 
        :
        :push(         )
                pop(         )
                shift(         )
                unshift(         )
                sort(    ,    ):arr.sort(function(a,b){return x( x    ,          。 x   ,          。 x 0,   。     return a-b    ,return b-a    )})
                                             sort        :xxx.sort(function(){ return Math.random()-0.5 })
                reverse(      )
                splice(  ):splice(      ,      ,          )
         :concat(    )
                  join(  ):join('x')  'x'         
                  split(  ):solit('x')  'x'         ,      
                  toString(     )
                  slice(  ):slice(       ,     )
               
  
    :
               
        length  
           push  ,    length             
       (  )  ,   length  ,    push  
 e.g. var obj={
        "2" : "a",
        "3" : "b",
        "length" : 2,
        "push" : Array.prototype.push
        }
        obj.push('c'); 
        obj.push('d');
            obj
        
       push    :
       Array.prototype.push=function(target){
            this[this.length]=target;
            this.length++;
       }
         obj.push('c'),   obj    obj[obj.length(  2)]='c',   length++
         obj.push('d'),   obj[3]='d'
            obj {
                        "2" : "c",
                        "3" : "d",
                        "length" : 2,
                        "push" : Array.prototype.push
                      }
        
        
        (       ):
 Array.prototype.unique=function(){
        var temp={};
        var arr=[];  //         
        var len=this.length;
        for(var i=0;i

Try...catch
 try       ,        try     ,            
try{

}catch(e){

}

       (error.name       ):
1. EvalError:eval()         
2. RangeError:    
3. ReferenceError:            
4. SyntaxError:        
5. TypeError:       
6. URLError:URL          

엄격 한 모드
"use strict"(           )
    es3        ,     es5  。
    :      
                  (  )
"use strict"       ,                  。
   with,arguments,callee,func,caller,         ,  this     (Person.call(null/undefined)        ),         

DOM 조작
DOM               。DOM        ,        。    html xml          。

        
 : (  getElementsById       ,           (      [n(0,1,2,...)]))
     document.getElementById('id ')     id       ( IE8         id    )
     document.getElementsByTagName('   ')               
     document.getElementsByName('name ')        name       
     document.getElementsByClassName('  ')               ( IE8 IE8        ,    class  )
     document.querySelector('CSS      ')      CSS         ( IE7 IE7       )      
     document.querySelectorAll('CSS      ')      CSS         ( IE7 IE7       )      
 :
    document.createElement():      
    document.createTextNode():      
    document.createComment():      
    document.createDocumentFragment():         (      DOM        DOM )
 :
           .appendChild(      ):             (       )
           .insertBefore(      ,           ):             
        insertAfter():
    Element.prototype.insertAfter(targetNode,afterNode){
        var beforeNode=afterNode.nextElementSibling;
        if(beforeNode==null){  //        ,         
            this.appendChild(targetNode);
        }
        else{   //            (            )
            this.insertBefort(targetNode,beforeNode);
       }
    }
 :
       .removeChild():        (    )
      .remove():        (    )
  :
       .replaceChild(new,origin):     
       
     :
parentNode:   (    parentNode #document)
childNodes:    
firstChild:      
lastChild:       
nextSibling:       
previousSibling:       

     :    (1)
               (2)
               (3)
               (8)
           document(9)
           DocumentFragment(11)
           
          :
parentElement:            (IE   )
children:             
node.childElementCount(   node.children.length):              
firstElementChild:         (IE   )
lastElementChild:          (IE   ) 
nextElementSibling:           
previousElementSibling:           
(IE      IE9 IE9        )

       :
nodeName:      ,       ,  
nodeValue:Text   Comment       ,   
nodeType:      ,  
attribute:Element       

       :Node.hasChildNodes()(        )

Element       :
innerHTML:  HTML    
innerText/textContent:        (innerText      ,textContent IE      )

Element       :
ele.setAttribute(   ,   ):      
ele.getAttribute(   ):      
     

날짜 개체
     
var date=new Date();
         :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

타이머
     :
    =setInterval(function(){
      .....
},1000)

     :
clearInterval(    )

     :
    =setTimeout(function(){
    .....
},1000)

     :
clearInterval(    )

창 속성 가 져 오기, dom 크기
          :
window.pageXOffset/pageYOffset(  /  ) (IE8/IE8     )
document.body/documentElement.scrollLeft/scrollTop (     )
(           (  ),     )
 :document.body.scrollLeft+document.documentElement.scrollLeft

       :getScrollOffset(){
                    if(0 && window.pageXOffset){
                        return{
                            x:window.pageXOffset,
                            y:window.pageYOffset
                        }
                     }  
                     else{
                         return{
                            x:document.body.scrollLeft+document.documentElement.scrollLeft,
                            y:document.body.scrollTop+document.documentElement.scrollTop
                         }
                     }
               }
       
       
       :
window.innerWidth/innerHeight(       )(IE8/IE8     )
document.documentElement.clientWidth/clientHeight(            )
document.body.clientWidth/clientHeight(            )
         :document.compatMode:CSS1Compat(    ),backCompat(    )

       :getViewportOffset(){
                    if(0 && window.innerWidth){
                        return {
                            w:window.innerWidth,
                            h:window.innerHeight
                        }
                    }
                    else{
                        if(document.compatMode==='BackCompat'){  //     
                            return {
                                w:document.body.clientWidth,
                                h:document.body.clientHeight
                            }
                        }
                        else{
                            return {
                                w:document.documentElement.clientWidth,
                                h:document.documentElement.clientHeight,
                            }
                        }
                    }
              }


         :domEle.getBoundingClientRect()
                         ,  left,top,right,bottom,width,height   ( width,height IE        )
                          
                
       :dom.offsetWidth,dom.offsetHeight
       :dom.offsetLeft,dom.offsetTop
               dom.offsetParent(           ,     body。body.offsetParent  null)
               
    :getElementPosition(         )

           :scroll(x,y):   ...
                      scrollTo(x,y):   ...
                      scrollBy(x,y):   ...(   )
                      

스 크 립 트 화 CSS
    css  :
dom.style.prop
       ,       ,  float        ,    css( float --> cssFloat)
        
            

      :
window.getComputedStyle(ele,null)[prop]
      
              ,      
IE8 IE8      
null        ,  null( :window.getComputedStyle(ele,'after').width)

    (IE8 IE8    ,IE  ):ele.currentStyle.prop
      
                   

       :getStyle(ele,prop){
                    if(window.getComputedStyle){
                        return window.getComputedStyle(ele,null)[prop]; 
                    }
                    else{
                        return ele.currentStyle.prop;
                    }
                }
                

이벤트
        :
 ele.onxxx=function(e){}      ,                         this      
 obj.addEventListener(type,fn,false){} IE9     ,                this      
 obj.attachEvent('on'+type,fn){} IE  ,                  this  window
 
           :addEvent(ele,type,handle){
                        if(ele.addEventListener){
                            ele.addEventListener(type,handle,false);
                        }
                        else if(ele.attachEvent){
                            ele.attachEvent('on'+type,function(){
                                handle.call(ele);
                            })     
                        }
                        else{
                            ele['on'+type]=handle;
                        }
                     }
                     
        :
ele.onclick=false/null/''
ele.removeEventListener(type,fn,false)
ele.detachEvent('on'+type,fn)
 
      :
    :   (    )       ,          ,     ,          (    )
(focus,blur,change,submit,reset,selectd      )
        :e.stopPropagation()(   IE9     )
                 e.cancelBubble=true(IE  )

    :   (    )        ,          ,     ,          (     ) (    ) IE      
 addEventlistener        true       

    :      

      (    ,a    ,     ):
return false:                
e.preventDefault() (IE9     )
e.returnValue=false (  IE9)

    :
event( IE     ) || window.event(  IE   )

     :
event.target (      )
event.srcElement (IE    )
    chrome  

    :
                
  :                   
        ,                
      
    :
    :click,mousedown,mousemove,mouseup,contextmenu,mouseover,mouseout,mouseenter,mouseleave
event  button         (   0,   2)

    :keydown,keyup,keypress(keydown > keypress > keyup)
keydown keypress   :keydown         
                        keypress          ,   ASCII         
                        
      :input(        ),focus,blur,change(          )

     (window    ):scroll,load

JSON
         (      ,      ,      ,        ,json      )
JSON ,         
JSON.parse():string -> json
JSON.stringfy():json -> string

비동기 로드 js
js     :             ,  js         ,      ,         js             

js         :
1. defer    ,  dom            。  IE  ,         。
2. async    ,      ,async        ,   js  script   
3.   script,   DOM ,     callback
(                   )

js 불 러 오 는 타임 라인
1.   Document  ,    web  。  HTML             Element   Text      。 (document.readyState='loading')
2.   link  css,      ,       
3.   script  js,      async,defer,     ,   ,  js          ,        
4.   script  js,     async,defer,         ,       。  async     ,           。(      document.write())
5.   img ,     dom  ,         src,       
6.        ,document.readyState='interactive'
7.        ,     defer          
8. document    DOMContentLoaded  ,                ,         
9.    async           ,img      ,document.readyState='complete',window    load

정규 표현 식
    :'\'
/^  ,  $/
       :                      

      :   (  ):var reg=/.../(    i(     )/g(    )/m(    ))
             new RegExp():var reg=new RegExp('...','i/g/m')
             
         :reg.test(str)(          。   true   false)
                   reg.exec(str)(          。      ,      )
                   ...
                   
        string     :str.match(reg)(           ,                )
                                str.search(reg)(             。  str      reg           ,            ,  -1)
                                str.replace(reg/str,replacement)(            ,                )
                                ...

                 :\w===[0-9A-z_],\W===[^\w]
                                  \d===[0-9],\D===[^\d]
                                  \s===[\t
\r\v\f],\S===[^\s] \b=== ,\B=== .===[^\r
] :n+( ) n*( 0 ) n?( 0 1 ) n{x}( x ) n{x,y}( x y ) ( ) ( ):?=xxx( xxx ) ?!xxx( xxx ) ( ):?<=xxx( xxx ) ? true e.g.2 var reg=/^\d[\s\S]*\d$/g; var str='123abc123'; reg.test(str) -> true e.g.3 replace var str='aa'; //var reg=/a/; console.log(str.replace('a'/reg,'b')) ba( ) var reg=/a/g; console.log(str.replace(reg,'b')) bb( ) e.g.4 aabb bbaa var reg=/(\w)\1(\w)\2/g; var str='aabb'; console.log(str.replace(reg,'$2$2$1$1')); :console.log(str.replace(reg,function($,$1,$2){ return $2+$2+$1+$1 })); e.g.5 ( , ) var str='10000000000'; var reg=/(?=(\B)(\d{3})+$)/g; str.replace(str,'.'); :https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp https://www.w3school.com.cn/jsref/jsref_obj_regexp.asp

약간의 잡동사니
     var   ,    window    ,             ,delete  
undefined null      
typeof(arguments):object
document.documentElement  html
       ,  ?       

좋은 웹페이지 즐겨찾기