JavaScript学习—闭包和this

一、闭包

JavaScript变量作用域分:全局变量和局部变量。函数内部可以直接读取全局变量,函数外部无法读取局部变量。

在一个函数A的内部定义一个函数B,函数B称为闭包。闭包作用如下:

(1)读取函数内部的局部变量

function k1(){

var n = 99;

function k2(){alert(n);}

k2(); //闭包只能在函数内执行

}

k1();

k1.k2(); //出错

function b(){

var n=99;

function m(){return n;}

return m();} 

alert(b()); //99

(2)让特定的变量值始终保存在内存里

function k1(n){

this.n = n;

this.nadd = function(){n += 1;}

this.k2 = function(){alert(n);}

}

var x = new k1(99);

x.k2(); //99

x.nadd();

x.k2(); //100

变量n的值一直保存在内存中。

区别举例:

function k1(){var n = 99; function k2(){alert(n);} return k2();} k1();

k1:{k2:{var n=99;alert(n);}} k1.k2;

function k1(n){this.n=n; this.k2=function(){alert(n);}} var x=new k1(99); x.k2();

二、关键字this

1. this概述

当一个函数创建后,一个关键字this就随之创建,它链接到一个活动对象(函数该活动对象中运行),关键字this可在函数中使用,是对活动对象的引用,而函数正是该对象的属性或方法。

var x = {

  name:'david',

  age:23,

  gender:'male',

  getGender:function(){return this.gender;}

};  

alert(x.getGender()); //male

2. this动态取值

this动态取值取决于函数什么时候被调用。

var x ='hello';

var mObj = {x:'mObj.hello'};

var dox =function() {alert(this['x']);};

mObj.dox = dox;

mObj.dox(); //mObj.hello

dox(); //hello this指向head对象(windows)

在ECMA3中嵌入函数的this指向head对象(windows),ECMA5中修改了这个问题。

var mObj = {

f1:function() {

     alert(this); /*mobj*/

     varf2=function() {alert(this);}(); /*window*/

   }};

mObj.f1();

3. 使用call、apply和bind控制this的值

function print(text){alert(this.value +' - ' + text+'');}  

var a = {value: 10, print : print}; 

var b = {value: 20, print : print}; 

print('hello'); //this => global, output "undefined - hello"

a.print('a'); //this => a, output "10 - a"

print.call(a,'a'); //this => a, output "10 - a"

print.call(b,'b');// this => b, output "20 - b"

print.apply(a, ['a']); //this => a, output "10 - a"

print.apply(b, ['b']);// this => b, output "20 - b"

var q = print.bind(a);

q('a');             //this => a, output "10 - a"

q.call(b,'b');     //this => a, output "10 - b"

q.apply(b, ['b']);  //this => a, output "10 - b"

4. 构造函数中this的取值

创建构造函数,使用new来创建实例对象,this指向实例对象。

var men=function(name) {this.name = name;}

var x=new men(Cody);

alert(x.name); //Cody

var Person =function(x){if(x){this.fullName = x};}; 

Person.prototype.fullname =function() {return this.fullName;}  

var cody =new Person('cody lindley');

alert(cody.fullname());



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值