javascript中的回调函数

本文介绍了JavaScript中回调函数的基本用法及高级应用技巧。通过实例展示了如何在匿名函数中使用回调函数,并探讨了如何通过不同方式传递参数给回调函数,包括使用`call`和`apply`方法。
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>回调函数使用</title>
	</head>

	<body>
		<!--一。基本用法-->
		<script language="javascript" type="text/javascript">
			//回调函数基本用法:
			//		function dosomeThing(callback){
			//			callback("我是","回调",'函数');
			//		};
			//		function foo(a,b,c){
			//			alert(a+b+c);
			//		};
			//		dosomeThing(foo);

			//匿名函数中使用回调函数:
			//			function dosomeThing(domsg, callback) {
			//				alert(domsg);
			//				if(typeof callback == "function") {
			//					callback("回调函数中的","参数");
			//				};
			//			};
			//			dosomeThing("匿名函数", function(a,b) {
			//				alert("此处是匿名函数中使用回调函数;"+a+b);
			//				
			//			});
		</script>

		<!--二。高级用法-->
		<!--<script language="javascript" type="text/javascript">
			function Thing(name) {
				this.name = name;
			};
						Thing.prototype.doSomething = function(callback) {
							callback.call(this);
						};
			function foo() {
				console.log(this.name);
			};
			var t = new Thing("Joe");
			t.doSomething(foo);
		</script>-->
		<!--传参数-->
		<!--<script type="text/javascript">
			function Thing(name){
				this.name=name;
			};
			Thing.prototype.doSomething=function(callback,parameterss){
				callback.call(this,parameterss);
			};
			function foo(parameterss){
				console.log(parameterss+" "+ this.name);
			};
			var t=new Thing("Joe");
			t.doSomething(foo,"Hi");
		</script>-->
		<!--使用 javascript 的 apply 传参数-->
		<script type="text/javascript">
			function Thing(name) {
				this.name = name;
			};
			Thing.prototype.doSomething = function(callback) {
				callback.apply(this, ['Hi', 3, 2, 1]);
			};

			function foo(parameterss, three, two, one) {
				console.log(parameterss + " " + this.name + " " + three + two + " " + one); //输出:Hi Joe321
			};
			var t = new Thing("Joe");
			t.doSomething(foo);
		</script>
	</body>

</html>

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值