js this作用域和用法详解

我来纠错
this是Javascript语言的一个关键字。 它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

//案例1:
function test(){
	console.log(this==window); //输出true,默认this是指window
};
test();

//案例2:
function test(){
	console.log(this==window); //输出false,如果构造函数里this就是函数本身
};
new test();

//案例3:
var test = {
	aa:function(){
		this.bb(); //这里的this,就是对象test
	},
	bb:function(){
		alert('我是bb方法');
	}
};
test.aa();

//案例4,不同作用域调用this:
<span class="btn">点击按钮</span>
<script src="js/jquery-1.7.js"></script>
<script>

$(document).on('click','.btn',function(){
	var self = this; //将点击的this对象,赋值给self,方便在其他作用域调用
	setTimeout(function(){
		alert($(self).text()); //弹出按钮的文字
	},1000);
});

</script>
发送
热门关键词:
命令
知识类型:
标题描述:
详细解答:

提交审核您编辑的知识会经过 前端大牛 人工审核。