Skip to content

回调函数 #46

Open
Open

Description

@Yangxiaqing

回调函数:

把一个函数A当做一个值传递给另外一个函数B,这样在B方法执行的时候,可以在任何位置执行一到多次A方法

		function A() {
			console.log('A');
		}
		function B(callBack) {
			console.log('B');
			callBack();
			for(var i = 0;i < 5;i++) {
				callBack();
			}
		}
		B(A);

回调函数应用:

1、

ary.sort(function (a, b) {
	return a - b;
});
str.replace(/\d+/g, function() {

});
window.setTimeout(function() {}, 10);

2、

function fn(callBack) {
	console.log(1);
	if(typeof callBack ===  "function") {
		callBack.();
	}
}
var obj = {fn: fn};
obj.fn(function () {
	console.log(this);//window
});
function fn(callBack) {
	//this->obj
	console.log(1);
	if(typeof callBack ===  "function") {
		callBack.call(obj, 100, 200);
	}
}
var obj = {fn: fn};
obj.fn(function (num1, num2) {
	console.log(this, num1, num2);//obj 100 200
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions