我遇到的一些问题(setInterval和setTImeout会导致与 this 绑定到全局对象运行...)

我遇到的一些问题(2019.4.28)

声明:本人还是一个大三小白,有错误请谅解。


一、setInterval和setTImeout会导致与 this 绑定到全局对象运行

var app = new Vue({
  el: '#app',
  data: {
    msg: '不要管',
    date: new Date(),
    name: 'huahua',
    age: '<p>28</p>',
    change: 'red',
    number: 1000
  },
  methods: {
    count: function() {
      console.log(this)
      this.number += 1
    }
  },
  filters: {
    filter: function() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDay()
      let sec = date.getSeconds()
      return year + '-' + month + '-' + day + '-' + sec
    }
  },
  mounted: function() {
    //注意setInterval中的this指向
    setInterval(function(){
      this.date = new Date()  //错误!
    }, 1000)
  }
})

在这段代码中,this指向window
改正: (让this指向vue实例)
(1)借助变量保存this

mounted: function() {
    //注意setInterval中的this指向
    let _this = this
    setInterval(function(){
      _this.date = new Date()  //错误!
    }, 1000)
  }

(2)利用箭头函数
使用es6中的箭头函数,因为在箭头函数中this是固定的。
箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。

mounted: function() {
    //注意setInterval中的this指向
    setInterval(()=>{
      this.date = new Date()  //错误!
    }, 1000)
  }

二、ASCII码 转换问题

// char-->ascii
  var a = 122;
      console.log("a".charCodeAt(0));
// ascii-->char
   String.fromCharCode(a);

三、getYear()和getFullYear()
之前以为获取完整年是getYear(),发现错了,getYear是1900开始的

new Date().getYear();    //116
new Date().getFullYear();    //2016
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值