class语法糖

  • class/constructor
  • extends/super
  1. class Animal{
  2. constructor(name){
  3. this.name = name;
  4. }
  5. jiao(){
  6. console.log("动物:"+this.name + "叫")
  7. }
  8. }
  9. class Cat extends Animal{
  10. constructor(name,age){
  11. super(name)
  12. this.age = age
  13. }
  14. jiao(){
  15. console.log("猫:"+this.name + "叫")
  16. }
  17. cry(){
  18. console.log("猫哭了" + this.age)
  19. }
  20. }
  21. let c = new Cat("kitty",12)
  22. c.jiao();
  23. c.cry();
  24. //猫:kitty叫 猫哭了

this

bind—给函数定死一个this,防止js的this乱变
箭头函数:根据所在环境,this恒定
普通函数:根据调用,this老变

箭头函数对this的优先级高于bind

  1. let obj={a : 1}
  2. let obj2 = {a : 2}
  3. obj.show = function(){
  4. return this.a;
  5. }
  6. console.log(obj.show())
  7. console.log(obj.show.bind(obj2)())
  8. // 1 2
  9. let arr = [1,2,3,4]
  10. arr.a = ()=>{
  11. console.log(this)
  12. }
  13. arr.b = function(){
  14. console.log(this)
  15. }
  16. arr.a() //{}
  17. arr.b() //[ 1, 2, 3, 4, a: [Function], b: [Function] ]