JavaScript__的this与函数

JavaScript 的this也遵循传递链机制,不懂该机制的同学请参考博文

简单的说就是内层找不到向上查找的机制

但是this 和 普通的用var声明的变量所走的是两套体系


如函数 

	showThisName = function() 
		{
			alert("xxx2");
			var name = "Haha";
			// 此时的this将引用到脚本所在的窗口
			alert(this.name);
		}

不会把name 当成当前的this, 会向上查找。看上层是否有this. 声明的变量

<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> new document </title>
</head>
<body>
<input type="button" value="按钮" name="bn"
	οnclick="showThisName();"/>
<script type="text/javascript">
	// 为当前的浏览器窗口的name属性赋值
	window.name = "测试窗口";
	alert("xxx0");
	var showThisName;
	var OuterFunction = function(){
		alert("xxx1");
		this.name = "OuterHaha";
		showThisName = function() 
		{
			alert("xxx2");
			var name = "Haha";
			// 此时的this将引用到脚本所在的窗口
			alert(this.name);
		}
	}
	OuterFunction();
</script>
</body>
</html>
点击按钮会找到外层OuterFunction的name



<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> new document </title>
</head>
<body>
<input type="button" value="按钮" name="bn"
	οnclick="showThisName();"/>
<script type="text/javascript">
	// 为当前的浏览器窗口的name属性赋值
	window.name = "测试窗口";
	alert("xxx0");
	var showThisName;
	var OuterFunction = function(){
		alert("xxx1");
		this.name = "OuterHaha";
		showThisName = function() 
		{
			alert("xxx2");
			this.name = "Haha";
			// 此时的this将引用到脚本所在的窗口
			alert(this.name);
		}
	}
	OuterFunction();
</script>
</body>
</html>
点击按钮会找到内层的showThisName的name



可以看到实际this.name会先查找 内层是否有定义this.name, 若没有会向上查找

但不会把局部变量 var name,当成this.name


附上一道思考题

六、思考题

如果你能理解下面代码的运行结果,应该就算理解闭包的运行机制了。

Js代码 
  var name = "The Window";   
  var object = {   
    name : "My Object",   
    getNameFunc : function(){   
      return function(){   
        return this.name;   
     };   
    }   
};   
alert(object.getNameFunc()());  
//The Window



<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> new document </title>
</head>
<body>
<script type="text/javascript">
	  var name = "The Window";   
  	var object = function(){
		this.name = "My Object";
	  	this.getNameFunc = function(){
		  return function(){
			  return this.name;
		  };
	  }
};
	  var kk = new object();
	  alert(kk.getNameFunc()());  //The Window
	 alert(kk.name);
</script>
</body>
</html>
运行截图


可以看出由于返回的是一个匿名函数,而对于JavaScript 来说函数永远独立,不从属于任何对象,所以打印出来的是

The Window,函数执行的时候是当前的环境而与外层无关故打印的是The window


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值