您的位置:首页 > Web前端 > JavaScript

JavaScript__的this与函数

2015-11-09 11:58 429 查看
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"
onclick="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"
onclick="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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: