JavaScript学习笔记(函数)

方式一定义函数:

function abs(x){
	if (x >= 0) {
		return x;
	} else{
		return -x;
	}
}
console.log(abs(-5));


上述函数的定义:

function指出这是一个函数定义;
abs是函数的名称;
(x)括号内列出函数的参数,多个参数以,分隔;
{ … }之间的代码是函数体,可以包含若干语句,甚至可以没有任何语句。

方式二定义函数

var abs = function(x){
	if (x >= 0) {
		return x;
	} else{
		return -x;
	}
}
//调用方式
console.log(abs(-58));
//传入为空时,输出NaN
console.log(abs());

为了避免发生undefined,可以对参数进行检查

function abs(x) {
	//判断x是否为number类型
    if (typeof x !== 'number') {
    	//抛出异常
        throw 'Not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}


arguments(用于判断传入参数的个数)
JavaScript还有一个免费赠送的关键字arguments,它只在函数内部起作用,并且永远指向当前函数的调用者传入的所有参数。arguments类似Array但它不是一个Array:

function foo(x){
	console.log('x = '+ x );
	for (var i = 0; i < arguments.length; i++) {
		console.log('arg'+i+'='+arguments[i]);
	}
}
console.log(foo(10,20,30,1));

function foot(a,b,c){
	if(arguments.length == 3){
		c = b;
		console.log("c="+c);
		b = null;
	}else{
		throw '参数太多了';
	}
}
console.log(foot(1,2,3));


rest
只能写在最后,前面用…标识,这是ES6标准引入的rest参数

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]

foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

在JavaScript引擎在行末自动添加分号的机制所以一般写成

function foo() {
    return { // 这里不会自动加分号,因为{表示语句尚未结束
        name: 'foo'
    };
}

名字空间:
全局变量会绑定到window上,不同的js文件如果使用了相同的全局变量或者定义了相同名字的顶层函数,都会造成命名冲突,并且很难被发现。
减少冲突的一个方法是把自己的所有变量和函数全部绑定到一个全局变量中。例如:

//定义唯一全局变量MAPP
var MAPP = {};

//其他变量
MAPP.name = 'myapp';
MAPP.version = 1.0;
MAPP.age = 18;
//其他函数
MAPP.foo = function(){
	return 'foot';
};
console.log(MAPP);

在这里插入图片描述
把自己的代码全部放入唯一的名字空间MAPP中,会大大减少全局变量冲突的可能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章