// 形参:形式上占位的参数,用于占位
function test(a, b) {
console.log(a, b); // 1 2
// arguments:函数的所有实参
console.log(arguments); // [1, 2]
// arguments.length:实参个数
console.log(arguments.length); // 2
}
// 实参:实际传入的参数
test(1, 2);
// 函数名.length:形参个数
console.log(test.length); // 2
总结:
// 初始化参数:默认值:undefined
function test(a = 1, b) {
console.log(a); // 1
console.log(b); // 2
}
test(undefined, 2);
// 函数的映射与返回
function test(a, b) {
// 函数内部能修改已经定义的实参值
a = 3;
console.log(arguments[0]); // 3
// 注意a与arguments[0]不是一个东西,但是存在映射关系,
// 函数内部认为对应值是一样的
// 函数内部不能修改未被定义的实参值
b = 3;
console.log(arguments[1]); // undefined
// 如果不写return,系统会自动添加一个this
return; //作用:终止函数执行、返回一个值
}
test(1);
// 函数内部可以访问并修改函数外部的变量
// 函数外部不能访问到函数内部的变量
var a = 1; // 全局变量
function test1() {
var b = 1; // 局部变量
console.log(a); // 1
function test2() {
var c = 3; // 局部变量
console.log(b); // 1
b = 2;
}
test2();
console.log(b); // 2
console.log(c); // ReferenceError: c is not defined
}
test1();
console.log(b); // ReferenceError: b is not defined
// 一个函数被调用时,累加它的实参值
function sum() {
var a = 0;
for(var i = 0; i < arguments.length; i++) {
a += arguments[i];
}
console.log(a); // 10
}
sum(1, 2, 3, 4);
// 1、普通函数默认返回undefined
// 2、构造函数通过实例化返回this
function Person() {
this.smoke = function() {
this.weight--;
}
}
Person.prototype = {
weight: 130
}
var person = new Person();
// 需要控制台feeble调用Person.smoke() 和person.smoke()