Program debugging / function / event / operation BOM object of JavaScript series

DOGIOOH 2020-11-13 01:49:49
program debugging function event operation


JavaScript Program debugging of series / function / event / operation BOM object

01 Program debugging

JavaScript Can be debugged directly in the web page , The method steps are as follows :

  • Open the web page —> Right click to check —>sources—> Breaking point —> Refresh web page —> Start debugging

Chrome Developer tools provide a variety of debugging methods :

  • Stop breakpoint debugging
  • Step by step debugging
  • step out
  • Remove breakpoint

In addition to using developer tools , You can also use alert() Method step by step debugging .


02 function

  • The concept of function

    Be similar to Java The method in , Is a block of code statements to complete a specific task . When the code repeats regularly , You need to abstract the code into functions , The function itself only needs to be written once , But it can be called multiple times .JavaScript Not only “ First-class citizen ”, And it can be used like a variable , Very powerful abstract ability .

    JavaScript The use of functions in is very simple , You do not need to define a class , You can use it directly .


  • Classification of functions

    Functions can be divided into system functions and custom functions

    • Common system functions are :
      • parseInt(“ character string ”);// Convert string to integer
      • parseFloat(“ character string ”);// Convert string to floating point number
      • isNaN();// Used to check whether its parameter is a number

  • How to define a function
// How to define a function ( One )
function method( Parameters ){
// Method body ;
//return; not essential
}
// How to define a function ( Two )
var Variable name = function ( Parameters ) {
// Method body ;
//return; not essential
};
// matters needing attention : Two definitions are completely equivalent , The second way is to add one at the end of the function body according to the complete syntax ;, End of assignment statement .

  • Call function

    • When calling a function, you can pass in parameters in order .
    function_name(parameter1,parameter2...);
    // matters needing attention :JavaScript Allow any parameter to be passed in without affecting the call , So there is no problem that there are more parameters passed in than defined , Even though these arguments are not required inside the function ; There are fewer parameters passed in than defined and no error will be reported , Returns the NaN.
    

  • Variable scope

    • If a variable is declared inside the function body , Then the scope of the variable is the whole function body , The variable cannot be referenced outside the function .
    • If two different functions declare the same variable , So this variable only works in its own function body .
    • JavaScript Functions of can be nested , here , Internal functions can access variables defined by external functions , Not vice versa .
    • JavaScript Functions of start from their own function definitions when looking for variables , from “ Inside ” towards “ Outside ” lookup . If the internal function defines a variable with the same name as the external function , The variables of the inner function will “ shielding ” Variables of external functions .
    • Variables that are not defined within any function have global scope .
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body onload="second( )">
    <script>
    var i=20;// Global variables
    function first( ){
    var i=5;
    for(var j=0;j<i;j++){
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;"+j);
    }
    }
    function second( ){
    var t=prompt(" Enter a number ", "")
    //second() Using global variables in i=20
    if(t>i)
    document.write(t);
    else
    document.write(i);
    first( );
    }
    </script>
    </body>
    </html>
    
  • Variable promotion mechanism

    JavaScript There is a feature of function definition of , It will scan the statements of the whole function body first , Put all declared variables “ promote ” To top of function , however JavaScript The engine only automatically promotes the declaration of variables , But it does not promote the assignment of variables . If the variable is called before a variable assignment statement , When the variable is executed, it is undefined type . So when we define variables within a function , To declare all variables inside a function first .


03 event

  • stay HTML Events can be added to tags , Events can be assigned , Call the function or method after the event is triggered. :
<input name="btn" type="button" value="button_name" onclick="method( )" />
  • There are several types of common events :
    • onload A page or an image is loaded
    • onlick Mouse click an object
    • onmouseover Mouse guide over an element
    • onkeydown A keyboard key is pressed
    • onchange Content of domain changed

04 operation BOM object

  • BOM: Browser object model ( Browser Object Model )

    • BOM Provides content independent , Object structure that can interact with browser windows .

    • window As a whole BOM At the heart of ,window Objects not only act as global scopes , And represents the browser window .

      window Objects have innerWidth and innerHeight attribute , You can get the inside width and height of the browser window . Inside width and height means removing the menu bar 、 The toolbar 、 After occupation elements such as border , Clear width and height used to display web pages .

    • BOM Realizable functions :

      • Pop up a new browser window
      • Move , Close and resize browser windows
      • Page forward , back off
        … …

  • Window object

    • Common properties :

      • history About the URL Information about
      //history Object holds the browser's history ,JavaScript You can call history Object's back() or forward (), It's equivalent to that the user clicks the browser's “ back off ” or “ Forward ” Button .
      // Be careful : This object belongs to the legacy object , For now , In any case , Neither should be used history This object .
      
      • location About the current URL Information about
      // Can pass location.href Get a complete URL
      // To get URL Value of each part , You can do this by
      location.protocol; // agreement
      location.host; // The host address
      location.port; // Port number
      location.pathname; // Path name
      location.search;
      location.hash;
      // To load a new page , You can call location.assign(). If you want to reload the current page , call location.reload() The method is very convenient .
      
    • Common methods :

      prompt( );// Displays a dialog box that prompts for user input , Two parameters , Input Dialog , Used to prompt the user to enter some information , single
      blow “ Cancel ” Button to return null, single click “ determine ” Button to return the value entered by the user . Often used to gather user feedback on specific issues .
      alert( );// Display a warning box with a prompt and a OK button , One parameter , Show messages for warning dialog only , No return value , No changes can be made to the script
      confirm( );// Display a prompt message 、 Dialog for OK and Cancel buttons . One parameter , Confirmation dialog , Show message for prompt dialog 、“ determine ” Button and “ Cancel ” Button , single click “ determine ” Button back true, single click “ Cancel ” Button back false, Therefore, if-else Statement collocation .
      close( );// Close the browser window
      open( );// Open a new browser window , Load given URL Specified document
      setTimeout( );// Call the function or computing expression after the specified millisecond count.
      setInterval( );// According to the specified period ( In milliseconds ) To call a function or expression
      

  • Document object

    • Common properties :

      • referrer Returns the URL. Can pass document.referrer Returns the link from which to jump to the current page .

      • URL Returns the URL

    • Common methods :

      getElementById();// Return to have specified id Reference to the first object of
      getElementsByName() ;// Returns a collection of objects with the specified name
      getElementsByTagName();// Returns a collection of objects with the specified label name
      write();// Write text to document 、HTML Expression or JavaScript Code
      
    • Dynamic change layer / Content in Tags

      • We can go through document Provided get Related methods get a node or a group of nodes , And dynamically modify the contents of this node .
      document.getElementById("id_name").innerHTML=" Replaced text ";
      

  • Date object :

    stay JavaScript in ,Date Object to represent date and time .

    // Get the current time of the system
    var now = new Date();
    document.write(now); // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
    document.write(now.getFullYear()); // year
    document.write(now.getMonth()); // month , Note that the month range is 0~11
    document.write(now.getDate()); // Japan , What's the number
    document.write(now.getDay()); // week , Day of the week
    document.write(now.getHours()); // when , 24 hourly
    document.write(now.getMinutes()); // minute
    document.write(now.getSeconds()); // second
    document.write(now.getMilliseconds()); // Number of milliseconds
    document.write(now.getTime()); // With number Time stamp of formal representation
    
    • Case study : Making clock effect in web page
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    #time{
    font-family: Microsoft YaHei ;
    font-size: 50px;
    }
    </style>
    </head>
    <body>
    <div id="time"></div>
    <input type="button" value="start" οnclick="startTime()">
    <input type="button" value="stop" οnclick="stopTime()">
    <script>
    var myTime;
    function clock() {
    // Get system current time
    var now = new Date();
    console.log(now);
    var hh = now.getHours();
    var mm = now.getMinutes();
    var ss = now.getSeconds();
    document.getElementById("time").innerHTML =" The time is now :" + hh + ":" + mm + ":" + ss;
    }
    function startTime() {
    myTime = setInterval("clock()",1000);
    }
    function stopTime() {
    clearInterval(myTime);// clear setInterval() Back to ID value , Cancel now setInterval Implementation
    }
    </script>
    </body>
    </html>
    

  • Math object

    • Common methods :

      ceil();// Round up logarithm Such as Math.ceil(25.5); return 26
      floor();// The logarithm is rounded down Such as Math.floor(25.5); return 25
      round();// Round a number to the nearest number
      random();// return 0~1 Random number between contain 0 It doesn't contain 1
      
    • Example : The integer range returned by the implementation is 1~100

      var num = Math.floor(Math.random()*99+1)// random Include obtained 0 It doesn't contain 1 The random number
      

版权声明
本文为[DOGIOOH]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple