0


JavaScript函数和window对象

函数(function)

函数的含义:类似于Java中的方法,是完成特定任务的代码语句块

使用更简单:不用定义属于某个类,直接使用

函数分类

  1. 系统函数
  2. 自定义函数
  • 有参函数
  • 无参函数
  • 函数的调用

定义函数

  1. 函数一定有返回(默认是未定义undefined)
  2. 可以写自己的返回
  3. return可以中断函数的运行
  4. 可以带参,不需要指定参数的类型,参数任意传,默认是未定义undefined
  5. 函数的返回值可以是任意类型

函数类型

  • 匿名函数(不定义名字)
  • 普通函数
  • 高阶函数(可以将函数作为参数)
  • 箭头函数(普通函数的简写)

各个函数类型的写法

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <!--onclick 当被点击的时候-->
  9. <button onclick="fb()">我是一个按钮</button>
  10. <script>
  11. /**
  12. public void fa(){
  13. }
  14. */
  15. //定义函数
  16. //1.函数一定有返回(默认是未定义undefined)
  17. //2.可以写自己的返回
  18. //3.return可以中断函数的运行
  19. //4.可以带参,不需要指定参数的类型,参数任意传,默认是未定义undefined
  20. //5.函数的返回值可以是任意类型
  21. function fa(a){
  22. console.log("hello");
  23. if(a){//为真
  24. return "yes"
  25. }
  26. return "no"
  27. }
  28. //匿名函数和调用的方式
  29. (function(){
  30. })();
  31. //调用函数
  32. console.log(fa());
  33. //可以将函数作为参数,这个就是高阶函数
  34. function fb(a,b){
  35. return a(b)
  36. }
  37. fb(fa,"1")
  38. //箭头函数 普通函数的简写
  39. var fb=()=>{
  40. document.write("调用了")
  41. }
  42. </script>
  43. </body>
  44. </html>

window对象

** window的含义:**是整个JavaScript中最大的对象

常用属性:

常用函数:

** 内置对象:**

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <a href="https://www.baidu.com">点我</a>
  9. <button onclick="f1()">点我</button>
  10. <h3 id="h3"></h3>
  11. <script>
  12. //写一个函数 接收两个参数 返回它们的和
  13. function a1(a,b){
  14. return a+b;
  15. }
  16. //window对象
  17. //是整个js中最大的对象
  18. // history 历史
  19. function back(){
  20. history.back()
  21. }
  22. function forward(){
  23. history.forward()
  24. }
  25. function f1(){
  26. //去百度
  27. location.href="https://www.baidu.com"
  28. }
  29. //window.xx()
  30. //window默认可以不写
  31. window.alert("我出来了")
  32. //定时炸弹
  33. /**
  34. setTimeout(function(){
  35. alert(炸了)
  36. },1000)
  37. **/
  38. var a=0;
  39. //i是定时器的编号
  40. var i=setInterval(function(){
  41. a++
  42. console.log(炸了)
  43. if(a==10){
  44. clearInterval(i);
  45. }
  46. },1000)
  47. setInterval(()=>{
  48. //textContent不识别html语句
  49. //现在的时间
  50. //h3.textContent=new Date();
  51. h3.innerHTML="<kbd>"+new Date().toLocaleTimeString()+"</kbd>"
  52. },1000)
  53. //new Date().getFullYear();
  54. //console.log(Math.max(1,2,3,4,5,6,7,8,9))
  55. //console.log(Math.min(1,2,3,4,5,6,7,8,9))
  56. //console.log(Math.ceil(1.99))//向上取整
  57. //console.log(Math.floor(1.99))//向下取整
  58. //console.log(Math.round(1.99))//四舍五入
  59. //随机出来的一定是小数[0,1)
  60. //1~10
  61. console.log(Math.floor(Math.random()*10)+1)//随机数
  62. </script>
  63. </body>
  64. </html>

本文转载自: https://blog.csdn.net/m0_67331668/article/details/123167632
版权归原作者 菲仔yo 所有, 如有侵权,请联系我们删除。

“JavaScript函数和window对象”的评论:

还没有评论