<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>函数,对象</title>
</head>
<body>
<script type="text/javascript">'use strict'//定义函数,两种方法//方法一function methods(x) {if (x < 0) {return -x;} else {return x;}}//方法二var xx = function (x) {if (x < 0) {return -x;} else {return x;}}//调用,传入的参数可多可少methods(2, 4, -6);//2methods();//undefinedxx(-2, 'r');//2xx();//undefined//防止undefinedvar xxx = function (x) {//类型比较,抛出异常if(typeof x !== 'number'){throw 'this is not a number';}if (x < 0) {return -x;} else {return x;}}xxx('a',12);//day03.html?_ijt=4heq2cefvmlfk3dcusn8rcuqga:37 Uncaught this is not a number//arguments只在函数内部起作用,指向当前函数调用者传入的所有参数,// 作用,可以拿到传入的所有参数,也就是说,即使不定义任何参数,也能获取传入参数的值function aa(){if (arguments.length === 0){return 0;}var y = arguments[0];return y>10?11:9;}aa(1);//9aa(33);//11//rest参数(es6引入)function bb(a, b, ...rest){console.log(a+':'+b);//1:2console.log(rest);//[3, 4]}bb(1,2,3,4)//变量作用域,var申明的变量是有作用域的//(1)函数体外不能引用函数体内的函数,因为使用了'use strict'严格控制模式function qq(){var j=9;j+=1;console.log(j);//j=10}j+=2;//Uncaught ReferenceError: qq is not defined//(2)函数可以嵌套,即函数里可以有函数,变量相同时,按照就近原则赋值function ww(){var y = 2;function pp() {var y='S';console.log(y);//y值为s}console.log(y);//y值为2pp();}//变量提升,即可以先使用,后定义,并不会报错,提升的是指未定义之前就用,//但是后面只能起申明,不能赋值function mm() {var x = 'w'+z;var y =12+zconsole.log(x);//x为wundefinedconsole.log(y);//y为NaNvar z = 3;}//全局作用域//不在函数体内定义的变量具有全局作用域,window是JavaScript默认的全局对象,// 实际上全局作用域的变量被绑到window的一个属性var d ='hello';alert(d);//helloalert(window.d);//hello//所以d与window。d作用是一致的,window是可省略的/*刚开始就说了,函数有两种定义方式,其实以变量方式 var x = function(){}定义的函数是一个全局变量* *///局部作用域:一般指变量的作用域是在函数内部,外部是无法使用的,但是,注意//for循环是无法定义局部变量的,即即使for中变量,也可以在当前函数体中使用function pp() {for (var i = 0; i <5 ; i++) {}i+=1;//不会报错,仍然可以使用变量i;console.log(i);//i值为6}/*但是上面显然很作用域很模糊,所有es6引入了新的关键字let,这个关键字可以是for中的变量的作用域只在for循环里面,出了for循环,就报错*/function kk(){for (let i = 0; i <5 ; i++) {}i+=1;//报错,ReferenceError: i is not definedconsole.log(i);}//常量/*es6,之前,想要声明一个变量是不可以的,通常把变量名大写来表示是一个变量,但是还是可以随便改变的,es6引入了新的关键字const定义常量*/const PI = 3.14;// PI = 4;//编译就报错//方法:在一个对象中绑定函数,称为这个对象的方法var per = {name:'大大',age: function () {return 18;}};console.log(per.name);//大大per.age();//18//标准对象typeof 123; // 'number'typeof NaN; // 'number'typeof 'str'; // 'string'typeof Math.abs; // 'function'typeof null; // 'object'typeof []; // 'object'typeof {}; // 'object'typeof true; // 'boolean'typeof undefined; // 'undefined'//Datevar now = new Date();now; // now.getFullYear(); // 2019, 年份now.getMonth(); // 0, 月份,注意月份范围是0~11,0表示一月now.getDate(); // 17, 表示17号now.getDay(); // 5, 表示星期五now.getHours(); // 24小时制now.getMinutes(); // 分钟now.getSeconds(); // 秒now.getMilliseconds(); //毫秒数now.getTime(); // 以number形式表示的时间戳</script></body>
</html>