js中this的指向

目录

普通函数中

对象的方法中

 属性在对象内部

构造函数中

绑定事件函数中

定时器中

立即执行函数


普通函数中

<script>
        function function1(){
            var a = 'apple';
            console.log("函数调用模式"+a);//a的值
            console.log(this);//window
            console.log(this.a);//undefined
        }
        function1();
</script>

 

 

对象的方法中

属性外对象外部

 //对象的方法调用模式
        var b = {
            name:'banana',
            sayName:function(){
                console.log("对象的方法调用模式"+this.name);//结果为banana,this代表b可获取到name
                console.log(this);//对象(object)
            }
        }
        b.sayName();

 

 结果为banana,this代表b可获取到name。

 属性在对象内部

var c = {
            name:'firstName',
            d:{
                name:'secondName',
                fn:function(){
                    console.log("对象的方法调用2"+this.name);//获取到seconName,this即指d这个对象
                    console.log(this);//对象(object)
                }
            }
        }
        c.d.fn();

 

 获取到seconName,this即指d这个对象。

构造函数中

//构造函数的调用模式
        function e(){
            console.log("构造函数的调用模式"+this);
        }
        var f = new e();
        //构造函数的调用模式2
        function g(){
            this.name = 'orange';
        }
        var h = new g();
       console.log(h.name);

 对象h自动获取到了构造方法g()中的属性,this代表g()中的对象

绑定事件函数中

 yellowStar.onclick = function (event) {
        console.log("星星执行了");
        if (this.getAttribute("src") == './images/star.png') {
            this.setAttribute('src', './images/stary.png');
        } else {
            // console.log("11");
            this.setAttribute('src', './images/star.png');
        }
    }

此例子为一个鼠标点击事件,通过点击获取到的星星DOM,改变其src值从而实现点击之后变换星星, this即为yellowStar.

定时器中

window.setTimeout(function() {
            console.log('定时器的this:' + this);
        }, 1000);

 指向的是window

立即执行函数

 (function() {
            console.log('立即执行函数的this' + this);
        })();

指向的仍然为window。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值