javascript笔记3

本文深入探讨了JavaScript中变量的作用域定义、函数调用者caller属性的应用、函数作为对象的特性、以及this关键字在不同上下文中的行为表现。

1、var定义的是作用域上的变量,没有var则是全局上的变量,var定义的变量不能再函数域中使用。

2、当javascript运行到一个函数时,会在当前作用域中建立一个子作用域,将当前作用域的全局性切换给这个新建的子作用域。

3、函数本身有个caller属性,调用函数调用者,全局调用者是null,上代码

<script type="text/javascript">

function whocallme(){
  alert("my caller is"+whocallme.caller);
}

function callA(){
	whocallme();
}
function callB(){
	whocallme();
}
alert(whocallme.caller);
callA();//mycaller is function callA(){}
callB();//mycaller is function callB(){}
whocallme();//输出my caller is null
</script>
caller属性opera浏览器不支持哦,其他浏览器基本支持。
4、javascript函数就是对象,这也是javascript特别之处,看个例子

<script type="text/javascript">



function sing(){
	alert(sing.author +" : "+sing.poem);
}
sing.author = "李白";
sing.poem= "白云依山尽"
sing();

sing.author="王维";
sing.poem="黄河入海流"
sing();
</script>

5、javascript中this作用

<script type="text/javascript">
function whoAmI(){
	alert("i am "+this.name +" of "+typeof(this));
}
whoAmI();//i am  of obhect
var Gates = {name:"bill gates"};
Gates.whoAmI = whoAmI;
Gates.whoAmI();//i am bill gates of object

var steven = {name:"steven"};
steven.whoAmI = whoAmI;
steven.whoAmI();//i am steven of object

whoAmI.call(Gates);//i am bill gates of object
whoAmI.call(steven);//i am steven of object

Gates.whoAmI.call(steven);//i am steven of object
steven.whoAmI.call(Gates);//i am bill gates of object
whoAmI.whoAmI = whoAmI;//将whoami函数设置为本身
whoAmI.name = "whoami";
whoAmI.whoAmI();//i am whoaimi of function
</script>
从上述代码可以看出this并不是指函数本身所属于的对象,this只是当前任意对象和function结合时的一个概念,在javascript中你只能把this看成当前要服务的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值