ES6

1.extends

class Point {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
    toString(){
        return this.x + ' ' + this.y;
    }
    
  }
class ColorPoint extends Point {
    constructor(x, y, color) {    
      //this.color = color; // ReferenceError
      super(x, y);
      this.color = color; //  正确
    }
    toString() {
        return this.color + ' ' + super.toString(); //  调用父类的 toString()
    }
  }
let cp = new ColorPoint(25, 8, 'green');
console.log(cp instanceof ColorPoint )// true
console.log(cp instanceof Point) // true
console.log(cp.x)//25
console.log(cp.toString())//green 25 8

2.箭头函数

前言:es6箭头函数没出现之前,this的指向不是函数被创建时绑定,而是被怎么样的方式调用时绑定的。而箭头函数刚好相反,箭头函数的this指向是函数被创建时绑定的,它的指向就是当前词法作用域中的this,并且不会因为被怎么样的方式调用改变绑定。

ES6中箭头函数VS普通函数的this指向_慕课手记  https://www.imooc.com/article/288214

function foo() {
    setTimeout(function(){
      console.log('id:', this.id);
    }, 100);
  }
  var id = 21;
  foo.call({ id: 42 });//21
  function foo1() {
    setTimeout(()=>{
      console.log('id1:', this.id1);
    }, 100);
  }
  var id1 = 21;
  foo1.call({ id1: 42 });//42
function Timer() {
    this.s1 = 0;
    this.s2 = 0;
    //  箭头函数
    setInterval(() => this.s1++, 1000);
    //  普通函数
    setInterval(function () {
      this.s2++;
    }, 1000);
  }
  var timer = new Timer();
  s2=0;
  setTimeout(() => console.log('s1: ', timer.s1), 3100);//3
  setTimeout(() => console.log('s2: ', timer.s2), 3100);//0
  setTimeout(() => console.log('s2: ', s2), 3100);//0
  console.log(s2);//0
 

 

var x = 11;
var obj = {
    x: 22,
    say(){
      console.log(this.x);
    },
    say1: ()=>{
        console.log(this.x);
    },
    say2:function(){
        var fn = () => console.log(this.x); // this指向obj对象
        return fn();
    },

}
obj.say();  // 22
obj.say1(); // 11
obj.say2(); // 22
const obj = {
  num: 10,
  hello: function () {
    console.log(this);    // obj
    setTimeout(function () {
      console.log(this);    // window
    });
  },  
  hello1: function () {
    console.log(this);    // obj
    setTimeout(() => {
      console.log(this);    // obj
    });
  }  
}
obj.hello();
obj.hello1();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值