http源码解读
什么是作用域?
作用域和调用函数访问变量的能力有关
作用域分局部作用域和全局作用域,同时作用域往往和变量有关系,
处在局部作用域里面可以访问到全局作用域的变量,反之则访问不到
实例如下:
var globalVariable = 'This is global variable'
function globalFunction(){
var localVariable ='This is local variable'
console.log('Visit global/local variable')
console.log(globalVariable)
console.log(localVariable)
globalVariable = 'This is changed variable'
console.log(globalVariable)
function localFunction(){
var innerLocalVariable = 'This is inner local variable'
console.log('Visit global/local/inner variable')
console.log(globalVariable)
console.log(localVariable)
console.log(innerLocalVariable)
}
localFunction()
}
globalFunction()
执行结果如下:
什么是上下文?
this关键字有关,是调用当前可执行代码的引用
常常代表this变量的值以及它的指向,它决定一个函数怎么被调用,当这个函数作为一个对象的方法被调用时this总是指向调用这个方法的对象
代码如下:
第一种
var pet = {
words:'...',
speak:function(){
console.log(this.words)
console.log(this === pet)
}
}
pet.speak()
执行结果如下:
第二种:
function pet(words){
this.words = words
console.log(this.words)
//这个this指向顶层的global对象
console.log(this === global)
}
pet('...')
执行结果如下:
第三种:
function Pet(words){
this.words = words
this.speak = function(){
console.log(this.words)
//此时的this指向的谁?cat对象
console.log(this)
}
}
var cat = new Pet('Miao')
cat.speak()
执行结果如下:
提出上下文是为了引出函数所拥有的两个方法:call和apply,可以改变上下文执行对象,可以在自定义上下文中执行函数,作用是一样的
只是用法有区别
call函数需要一个参数列表,apply允许你传递一个参数作为数组,具体的是作用呢是调用一个对象的方法以另一个对象替换当前对象,其实就是更改当前对象的this指向的内容,标准一点就是:以某个方法当做指定某个对象的方法被执行
示例如下:
var pet = {
words:'...',
speak:function(say){
console.log(say+' '+this.words)
}
}
//pet.speak('Speak')
var dog = {
words:'Wang'
}
//让dog也能有speak方法
pet.speak.call(dog,'Speak')
运行结果如下:
利用call和apply可以方便的实现继承
function Pet(words){
this.words = words
this.speak = function(){
console.log(this.words)
}
}
function Dog(words){
Pet.call(this,words)
//Pet.apply(this,arguments)
}
//通过new生成实例对象
var dog = new Dog('Wang')
dog.speak()
运行结果如下:
这就是call和apply的用法
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。