JavaScript this

this

this 本身原本很简单,总是指向类的当前实例。

this的特点:

  • 在 function 内部被创建
  • 函数预编译过程中,

    • this –> window(this指向window)
    • 全局作用域里this –> window
  • 指向调用时所在函数所绑定的对象

    • 谁调用这个方法,this就指向谁。obj.func(); func()里面的this指向obj)
  • this 不能被赋值,但可以被 call/apply 改变
    • call/apply可以改变函数运行时this的指向

例题:

<script type = "text/javascript"> 
    var name = "222";
    var a = {
        name : "111",
        say : function() {
            console.log(this.name);
        }
    }
    var fun = a.say;
    fun()               //222  将a.say放在全局执行
    a.say()             //111  a调用say方法
    var b = {
        name : "333",
        say : function() {
            fun();      //不像别的有调用:a.say,(前面有a.),这个没有,所以就执行预编译(全局的)
        }
    }
    b.say(a.say);          //222
    b.say = a.say;
    b.say();              //333

</script>

//222 111 222 333

练习题:

<script type = "text/javascript"> 
    var foo = 123;
    function print() {
        this.foo = 234;      //this表示的是window里面的,所以把GO的123改成了234   
        console.log(foo);    //指的是GO里面的123,但是前面有this的声明
    }
    print();                 
</script>
//234    

变形:

<script type = "text/javascript"> 
    var foo = 123;
    function print() {
        // var this = Object.create(print.prototype)  //这里的this不指代windowthis.foo = 234;      //AO里面没有foo,所以到GO里面去找 
        console.log(foo);    //指的是GO里面的123,但是前面有this的声明
    }
    new print();
</script>
//123   

例题:

运行test()和new test()的结果分别是什么?
<script type = "text/javascript"> 
    var a = 5;
    function test() {
        a = 0;
        alert(a);               //0     0
        alert(this.a);          //5     undefined
        var a;
        alert(a);               //0     0
    }
    test();
    new test();
</script>

解析:

test()
AO {
    a:undefined
    this.a:window
}
        |
 AO {
    a:0
    this.a:5
new test()
AO {
    a:undefined
    this.a:{}
}
        |

new的时候函数里面有var this = Object.create(test.prototype)
或者写成var this = {
                    __proto__:test.prototype

                   }
 AO {
    a:0
    this.a:undefined   //this上面没有a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值