浅谈javascript中this指向的问题

**在普通函数的中的this指向**
function test() {
var a = 1;
console.log(this.a);
console.log(window.a)
}
test()

在严格模式下的this指向问题
 var a = 1;
        function test (){
            'use strict';
            console.log(this);
            console.log(this.a);
        }
       test();
在 对象属性中方法中this指向问题
var obj = {
           a : 1,
           test: function () {
               console.log(this);
               console.log(this.a)
           }
       }

       obj.test()
函数参数传递是this指向的问题
function test (a) {
           this.a = a;
           console.log(this.a)
           console.log(window.a)
       }
    
     test(1)


function test (a) {
          this.a = a;
          console.log(this.a);

          return undefined;
      }
    
      test.prototype.say = function () {
          console.log(this.a)
      }
    
      test(1).say()


function test (a) {
          this.a = a;
          console.log(this.a);
      }
      test.say = function () {
          console.log(123)
      }
      test.prototype.say = function () {
          console.log(this.a)
      }
    
      test.say()
      
 var oBtn = document.getElementById('btn');

    oBtn.onclick = function () {
        console.log(this);
        this.innerHTML = "加载中...";
        this.disabled = true;
        var _self = this;

        setTimeout(function(){
            _self.innerHTML = "点击";
            _self.disabled = false;
        }, 2000);


        setTimeout(function(){
            this.innerHTML = "点击";
            this.disabled = false;
        }.bind(this), 2000);

        setTimeout(() => {
            this.innerHTML = "点击";
            this.disabled = false;
        }, 2000);

    }

  function Test () {
            this.oBtn = document.getElementById('btn');
            this.a = 0;
            this.init();
        }

        Test.prototype.init = function () {
            this.bindEvent();
        }

        Test.prototype.bindEvent = function () {
            this.oBtn.addEventListener('click', this.btnClick.bind(this), false);
            var _self = this;
            this.oBtn.addEventListener('click',function() {
                this.btnClick()
            }, false);
        }
       Test.prototype.btnClick = function () {
           this.a ++;
           console.log(this.a);
       }

       new Test()
    call/apply 改变this指向 并且立即执行
    写法不算区别
    call(context, 原函数的参数们依次排列);
    apply(context, 原函数的参数集合 用数组装载);
    bind    改变this指向  并返回一个新函数
    写法同call
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值