5、函数中的问题
1、重名:函数重名,后面的覆盖前面的
function fn() {
console.log(1);
}
fn();
function fn() {
console.log(2);
}
fn();
2、形参和实参个数不相等
- 实参比形参个数少,则没有匹配上的形参,值为undefined
- 实参比形参个数多,则多的也白多
function fn(a, b) {
console.log(a, b);
}
// fn(10, 20);
// fn(5);
fn(5, 10, 20);
3、this
var box = document.getElementById('box');
function fn() {
console.log(this);
}
// 第一种调用:函数名(),这样调用,函数中的this是window
fn();
// 第二种调用:函数被元素点击调用,函数中的this是哪个元素
box.onclick = fn;
box.onclick = function () {
// this --> box
fn(); // --> window
}
// ----------------------------
var obj = {
name: '张三',
fn: function () {
console.log(this);
}
}
// console.log(obj.fn);
// 第三种 :函数作为对象的方法调用,函数中的this就是这个对象
obj.fn();