参数函数
定义函数
1.绝对值
function abs(x) {
if (x>=0){
return x
}else
return -x
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eVoOd81D-1616384885267)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210316224157193.png)]
另一种定义方式:
var abs = function (x) {
if (x>=0){
return x
}else
return -x
}
参数:js可以传参数也可以不传
var abs = function (x) {
// 手动抛出异常来源来判断
if(typeof x !== "number"){
throw 'x is not a number'
}
if (x>=0){
return x
}else
return -x
}
arguments 是js 免费赠送的关键字
代表所有传进来的参数是一个数组
var abs = function (x) {
console.log("x=>"+x);
if(arguments.length>2){
for (var i = 0 ;i<arguments.length;i++){
console.log(arguments[i]);
}
}
rest ES6引入的新特性
function aaa(a,b,...rest) {
console.log("a=>" + a);
console.log("b=>" + b);
console.log(rest);
//以前: if (arguments.length>2){
// for (var i=2 ;arguments.length;i++){
// console.log(arguments[i]);
// }
}
2. 变量作用域
在js中,var定义变量实际是有作用域的
假设在函数体中申明,在函数体外不可以使用(非要实现:闭包https://www.runoob.com/js/js-function-closures.html)
两个函数使用相同的变量名,只要在函数内部,就不冲突
内部函数可以访问外部函数,反之则不行
假设,内部函数变量和外部函数变量重名:
function a() {
var x = 1;
function b() {
var x = "A";
console.log('inner'+x);//innerA
}
console.log('outer'+x);//outer1
b();
}
a();
js查找函数从自身变量开始,由“内”向“外”查找,假设外部存在则内部会屏蔽
js执行引擎,自动提升y的声明,但不会提升变量y的赋值
function a() {
var x = "x" + y;
console.log(x);
var y = "y";
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l0NH4oys-1616384885271)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210318204802326.png)]
变量定义放在函数头部
全局函数:
全局对象window
alert() 这个函数本身也是一个window
var x = 'aaa';
window.alert(x);
var old_alert = window.alert;
//old_alert(x);
window.alert = function () {
}
//alert()失效
window.alert(123);
//恢复
window.alert = old_alert;
window.alert(456);
由于所有的全局变量都会绑定到window上 如果不同的js文件会有冲突
把自己的代码放入自己定义的唯一空间名字 减少冲突
jQuery $
局部作用域 let
function aaa() {
for (var i= 0; i < 100; i++){
console.log(i)
}
console.log(i+1);
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PAv8146t-1616384885274)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210318212759828.png)]
function aaa() {
for (let i= 0; i < 100; i++){
console.log(i)
}
console.log(i+1);
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wRC4RWxN-1616384885277)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210318212826529.png)]
用let去定义局部变量
常量const
var PI = '3.14';
console.log(PI);
PI = "213";//可以改变这个值
console.log(PI);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EPIga5mA-1616384885279)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210318213135819.png)]
let s = '3.14';
const PI = s;
console.log(PI);
PI = "213";
console.log(PI);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5c37uNS6-1616384885282)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210318213209041.png)]
对齐 ctrl + alt + v
3.方法
apply关键字
var zzh = {
name: 'zzh',
birth: 2000,
age: getAge()
};
var dd = {
name: 'dd',
birth: 1999,
age: getAge()
};
function getAge() {
var now = new Date().getFullYear();
return now - this.birth;
}
getAge.apply(zzh,[]); //this 指向了 zzh,参数为空