_log = console.log
//参数默认值
function log(x,y = ‘world‘){
_log(`${x} ${y}`);
}
log(‘hello‘) //hello world
log(‘hello‘, ‘china‘) //hello china
function Point(x = 0, y = 0){
this.x = x;
this.y = y;
}
_log(new Point());
function add(x = 1){
let x = 2; //报错
const x = 3; //报错
}
//与解构解析配合
function foo({x, y=5}){
_log(x,y)
}
foo({}); //undefined , 5
foo({x:1}); //1 5
foo({x:1,y:10}); // 1 10
//foo() //报错
function fetch(url , {body=‘‘,method=‘GET‘,headers={} }){
console.log(method);
}
fetch(‘http://qq.com‘,{}); //GET
//fetch(‘http://qq.com‘); //报错
function fetch(url , {body=‘‘,method=‘GET‘,headers={}} = {}){
console.log(method)
}
fetch(‘http:qq.com‘);
function m1({x=0,y=0}={}){
console.log(x,y)
}
function m2({x,y} = {x:0,y:0}){
console.log(x,y);
}
m1(); //[00]
m2(); //[0,0]
m1({}); //[0,0]
m2({}); //[undefined,undefined]
//函数参数默认值,尽量放在尾部
function foo2(x, y=2){}
console.log(foo2.length)
//函数的length属性返回没有默认值参数的和
//作用域
var x = 1
function f(y=x){
console.log(y);
}
f(2);//2
/*function f2(y=x2){
let x2 = 2;
console.log(y); //报错
}
f2();
*/
/*let foo22 = ‘outer‘;
function bar22(func = x=> foo){
let foo = ‘inner‘;
console.log(func()); //outer
}
bar22();
*/