函数作用域的理解

本文通过实验探讨了JavaScript中函数参数作用域的特点,包括未传值时参数为undefined、传值时参数等于传入值以及函数内部声明变量时的取值规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数作用域的理解(1)

 var x={name:"one"};
    function test(x,y=function(){x.name = "two";console.log(x.name);}){//two
        var x={name:"three"};
        y();
        console.log(x);//three
    }
    test(x);
    console.log(x.name);//two
var x={name:"one"};
    function test(x,y=function(){x.name = "two";console.log(x.name);}){//two
        //var x={name:"three"};
        y();
        console.log(x.name);//two
    }
    test(x);
    console.log(x.name);two
var x={name:"one"};
    function test(x,y=function(){console.log(x.name);x.name = "two";}){//报错
        //var x={name:"three"};
        y();
        console.log(x.name);
    }
    test();
    console.log(x.name);

通过上面函数实验得知,test函数在初始化参数作用域时,参数作用域是拥有自己的独立作用域,它有一下表现:
1.如果没有传值,则x为undefined,尽管y函数定义了x,但是他不属于这个作用域,它属于这个作用域的子作用域;

var x={name:"one"};
    function test(x,y=function(){var x = {name:"two"};}){
        //var x={name:"three"};
        y();
        console.log(x.name);//报错
    }
    test();
    console.log(x.name);

2.如果传入值,则参数等于(=)传入的值;y函数是单独作用域,不会影响test的作用域,如果y中没有声明,则会x指向传入对象,会影响外部x的值

var x={name:"one"};
function test(x,y=function(){var x = {name:"two"};}){
        //var x={name:"three"};
        y();
        console.log(x.name);//one
    }
    test(x);
    console.log(x.name);//one
var x={name:"one"};
    function test(x,y=function(){x.name = "two"}){
        //var x={name:"three"};
        y();
        console.log(x.name);//two
    }
    test(x);
    console.log(x.name);//two

3.函数内部的作用域如果有声明,则取内部声明的参数,如果没有,则取参数声明的变量,但y函数属于独立的作用域,相当于并列的关系,它声明的变量不会影响test内部;

var x={name:"one"};
    function test(x,y=function(){var x={name:"two"};}){
        var x={name:"three"};
        y();
        console.log(x.name);//three
    }
    test(x);
    console.log(x.name);//one
var x={name:"one"};
    function test(x,y=function(){var x={name:"two"};}){
        x.name="three";
        y();
        console.log(x.name);//three
    }
    test(x);
    console.log(x.name);//three
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值