上下文:this变量的值,以及他的指向。

 

function pet (words) {
    this.words = words
    
    console.log(this.words)      // ...
    console.log(this === global) //true
}
pet('...') //全局调用

js中this指向函数的拥有者,通常将拥有者叫执行上下文。this只能在函数内部使用。

this指向:

1、函数拥有者

2、全局

3、在构造函数中的this,是指向新创建的实例对象

 

上下文可以在执行环境中被改变。

call()//参数列表

apply([,...args])//参数数组

 

也可以实现继承:

 1 function Pet (words) {
 2     this.words  =words
 3     this.speak  =function() {
 4         console.log(this.words)
 5     }
 6 }
 7 function Dog (words) {
 8     Pet.call(this, words)//将Pet的this指向当前的Dog
 9     //Pet.apply(this, [])
10 }
11 var dog = new Dog('Wang')
12 dog.speak()

 

相关文章:

  • 2021-11-14
  • 2021-10-02
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
  • 2021-10-23
  • 2022-12-23
猜你喜欢
  • 2021-09-25
  • 2022-12-23
  • 2021-09-11
  • 2021-07-23
  • 2022-12-23
  • 2021-08-22
相关资源
相似解决方案