作用域和上下文

上下文: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()

 

posted @ 2017-05-26 15:03  九许尘歌  阅读(165)  评论(0编辑  收藏  举报