1:一次封装(定义),四处使用(调用)
//一般情况下的样子
function add(num1, num2) { //命名函数
return num1+num2;
// 这里的return 有两种含义,第一种此函数执行到此结束,第二层含义 ,返回值。
}
add(1,1);
add(1,2);
add(1,3);
window.onload = function(){} //没有名字的函数是匿名函数
为何要使用函数
1:复用代码
2:统一修改和维护
3:增加代码可读性
function doThings(month) {
if (month >= 3 && month <= 5) {
console.log("踏春");
} else if (month >= 6 && month <= 8) {
console.log("游泳");
} else if (month >= 9 && month <= 11) {
console.log("秋收");
} else {
console.log("睡觉");
}
}
doThings("6");
function isSpring(month) {
return month >= 3 && month <= 5;
}
function isSummer(month) {
return month >= 6 && month <= 8;
}
function isAutumn(month) {
return month >= 9 && month <= 11
}
// 修改之后更加语义化代码
function doThings(month) {
if (isSpring(month)) {
console.log("踏春");
} else if (isSummer(month)) {
console.log("游泳");
} else if (isAutumn(month)) {
console.log("秋收");
} else {
console.log("睡觉");
}
}
doThings("9");
1-3 函数的本质
二像性, 调用 和对象。
函数自定的方式 字面量如下{}
function add(num1,num2){}
构造函数的方式
new Function('num1','num2');
函数也是对象 添加属性和方法
function add(num1,num2){
return num1 + num2;
}
add.sex= 'male';
add.setSex = function(sex){
this.sex = sex;
}
console.log(add.sex);
console.log(add.setSex("female"));
console.log(add.sex);
console.log(add(1,2));
函数作为数据值使用
var add = function(){
}
//现在那是将一个匿名函数赋值给一个变量
console.log(add()); //返回的是函数的返回值
console.log(add)//返回的是函数本身
函数作为参数来使用
setTimeout(function(){
console.log("1");
},1000)
setTimeout(fn,1000);
function fn(){
console.log(1);
}
//作为返回值
function fn(){
return function(){
console.log(1)
}
}
var NewFn = fn()
NewFn();
函数的三种定义三方式
字面量
//第一种:function 声明
function add(){
//body
}
add()
// 第二种 var 赋值表达式
var add = function (argument){
};
add();
// 第三种构造函数
var add = new Function("num1","num2","return num1 + num2 ");
// 这里面的代码都是字符串的形式 不是变量的形式。
// 三种定义函数的方式 最终的区别是 预解析 预解析 预解析
定义函数的位置
//关系函数作用域,作用域链的问题。
function add() {
fn();
function fn() {
fn();
function fn3(argument) {
}
}
function fn2() {
fn();
}
}
![这里写图片描述](http://img.blog.csdn.net/20170604181418296?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzE2NTgwNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
// if for
if (true) {
function add(argument) {
// body...
}
} else {
function subtract(argument) {
}
}
// 理想情况下 true 定义加法函数 false 定义减法函数 其实这样是不可以的。在js中没有块级作用域
if (true) {
var add = function(argument) {
// body...
}
} else {
var subtract = function(argument) {
}
}
//预解析 add = undefined;subtract = undefined 当执行到add的时候add,重新赋值为 add = function(argument){}
//对象
var person = {
name = "xm",
setSex = function(sex) {
this.sex = sex;
};
person.setName = function(name) {
this.name = name;
}
}
person.setSex();