作用域
function(){}大括号中的内容是一个作用域;
function 和 var 的声明会被提到作用域的最上面
function f(){
a = 2;
var b = g(); //此处可以访问到g()函数
a=3;
return b;
function g(){ //函数的声明会被提前到作用域顶部
return a;
}
a=1;
}
var result = f();
console.log(f()); //2
console.log(a) //3 a未被声明,那么就会在全局作用域被声明;
// 如果a被在f()中声明,那么全局作用域则访问不到
// 如果a在全局和局部作用域都被声明:那么两个a互相不干扰
调用函数访问变量的能力
//全局变量
var globalVariable = 'This is global variable'
//全局函数
function globalFunction(){
//局部变量
var localVariable = 'This is local variable'
console.log('visit gloabl/local variable')
console.log(globalVariable)
console.log(localVariable)
globalVariable = 'this is change variable'
console.log(globalVariable)
//局部函数
function loaclFunction(){
//局部变量
var innerLocalVariable = 'this is inner local variable'
console.log('visit gloabl/local/innerLocal variable')
console.log(globalVariable)
console.log(localVariable)
console.log(innerLocalVariable)
}
//作用域内可访问局部函数
loaclFunction()
}
//在全局不能访问局部变量和函数
globalFunction()
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yMwMzN0cDN2MTMtEDO1QTMwAjMxcjM1ADOxAjMtATO2ADM58CX1ADOxAjMvwFM5YDMwkzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzcldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
上下文
和this关键字有关,是调用当前可执行代码的对象的引用
this指向函数拥有者,只能在函数中使用
this指向构造函数
var pet = {
words:'..',
speak:function(){
console.log(this.words)
console.log(this==pet)
}
}
pet.speak()
this指向全局对象
function pet(words){
this.words = words
console.log(this.words)
console.log(this==global)
}
//this指向了全局global对象
pet('..')
this指向实例对象
function Pet(words){
this.words = words
this.speak = function(){
console.log(this.words)
console.log(this)
}
}
var cat = new Pet('Miao')
cat.speak();
使用call和apply改变上下文引用对象
this指向引用方法的对象
var pet = {
words:'..',
speak:function(say){
console.log(say + ' ' + this.words)
}
}
pet.speak('haha')
使用call-apply
var pet = {
words:'..',
speak:function(say,free){
console.log(say + ' ' + free+ ' '+ this.words)
}
}
var dog={
words:'wawa'
}
pet.speak.call(dog,'haha','lala')
pet.speak.apply(dog,['haha','lala'])
使用call和apply方便实现继承
function Pet(words){
this.words = words
this.speak = function(){
console.log(this.words)
}
}
//Dog继承Pet,拥有了Pet的speak方法
function Dog(words){
Pet.call(this,words)
}
var dog = new Dog('wawa')
dog.speak()