var x =1;functionf1(x, y = x){
console.log(y)}f1(2);// 2// 调用函数时,将对x赋值为2,而y的默认值等于变量xvar x =1;functionf2(y = x){
console.log(y)}f2()// 1// y的值会指向全局的x,故值为1// 如果外部没有指定x,则会报错
var x =1;functionfooFun(x,y=()=>{ x =2}){var x =3;// 此处重新在fooFun内部声明了一个x,与参数中的x不属于同一个作用域y();// 参数作用域 内部的匿名函数中x指向第一个参数,且 x 由 undefined => 2
console.log(x)// 不会改变值,依旧是3}fooFun()// 3
console.log(x)// 1var x =1;functionfooFun1(x,y=()=>{// 此时是x=3,是fooFun1内部对x赋值成了3
console.log("Anonymous function inner x: ", x);
x =2;}){
x =3;// 此处x指向第一个参数,与匿名函数内部的一致
console.log("fooFun1 funtion inner x (param domain x): ", x)// 此时为仍然为3y();// 参数作用域 内部的匿名函数中 x 指向第一个参数,且 x 由 3 => 2
console.log(x)// 值更改成为2}fooFun1()// 2
console.log(x)// 1 不会更改外部的x
二. call、apply、bind异同
1. 三者都是改变函数的this指向
2. call、apply 都是第一个更改this指向,并立即执行
3. bind函数则会返回一个函数
4. call、bind是第二个参数是rest参数,apply第二参数是数组
PS: 🚀 talk is cheap, show me the code!
var lzx = Object.create({},{
status:{
value:"单身🐶",
writable:false,},
age:{
value:21},
sex:{
value:"man",
writable:false},
todo:{
value:function(value, msg){
console.log("汪汪汪..., ",this.status,"is calling, ", value, msg,this)}}})let cjt ={
status:"Godness",
age:23,
sex:"girl",todo(value){
console.log("Hey, lzx!", value)}}// 三者都是改变this指向// call, apply 都是第一个更改this指向,并立即执行, bind函数则会返回一个函数
lzx.todo("This is a normal function!, ","Hey Boy!")// call 可以传递rest参数
lzx.todo.call(cjt,"This is a call function!, ","Hey Girl!")// apply 只能第二参数只能传递数组
lzx.todo.apply(cjt,["This is a apply function!, ","Hey Girl!"])// bind 需要返回一个新的函数,执行该新函数,才与call相似let newBindFun = lzx.todo.bind(cjt,"This is a bind function!, ","Hey Girl!")newBindFun()// bind绑定过的函数无法通过apply或者call改变this指向let testObj ={
status:"testObj"}
newBindFun.call(testObj)