Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js this 指向 #75

Open
gaowei1012 opened this issue Apr 11, 2021 · 1 comment
Open

js this 指向 #75

gaowei1012 opened this issue Apr 11, 2021 · 1 comment

Comments

@gaowei1012
Copy link
Owner

在浏览器非严格模式下,this 指向的是 window

// 浏览器环境下
 console.log('this A=====>>>', this)
// {}

在块级作用域内

// 此时的this指向就是指向就是他自己
const test = {
  prop: 42,
  func: function() {
    // console.log('this B=====>>>', this)
    // { prop: 42, func: [Function: func] }
    return this.prop;
  },
};
@gaowei1012
Copy link
Owner Author

gaowei1012 commented Apr 11, 2021

class 中比较特殊,两个类的继承,继承的类要使用 super()才可以访问到 this

class A {
  constructor() {
    this.a = 'hello'
    this.b = 'world'
  }
  getName() {
    return '执念'
  }
}
class C extends A {
  constructor() {
    super() // 自动继承A类中的方法属性
    this.prop = {
      a: 10
    }
  }
  getThis() {
    // 这里的this指向的值当前C类
    // 这里有一个点需要注意,在class的继承过程中
    // 子类继承父类的时候,必须使用 super() 方法,才可以继承父类的方法和属性
    // 在此之前 this 是访问不到的
    console.log('class this ===>>', this)
    return this
  }
}

const c = new C()
console.log('c.getThis()=====>>>', c.getThis())
console.log('c.getName()=====>>>', c.getName())

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant