作用域和上下文

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

 

转载于:https://www.cnblogs.com/zuojiayi/p/6908561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值