JS回调函数的理解

文章摘抄 http://www.jb51.net/article/59447.htm

文章摘抄 http://www.jb51.net/article/53027.htm

 

JS Api 里这样解释:A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

我的理解就是方法名称作为参数传递到parent方法,parent方法执行完了之后再执行接收的参数(方法名称)

 

1.基本方法

 

function doSomething(callback) {
// … 
// Call the callback
    callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
    alert(a + " " + b + " " + c);
}
doSomething(foo);

 

 

用匿名函数的形式

 

function dosomething(damsg, callback){
    alert(damsg);
    if(typeof callback == "function")
        callback();
}
dosomething("回调函数", function(){
    alert("和 jQuery 的 callbacks 形式一样!");
});

 

 

高级方法,使用call 或者apply

 

 

function  a(callback){
	alert('a');
//或者是 callback(),  callback.apply(this),看个人喜好
	callback.call(this);
}
function  b(){
	alert('b');
}
//调用
a(b);   

 

 

匿名函数

function  c(callback){
    alert('c');
    callback.call(this,'d');
}
//调用
c(function(e){
    alert(e);
});

 

jquery实现代码

_$.prototype={
    bind:function(evt,callback)
    {
        var   that=this;
        if(document.addEventListener)
        {
            this.element.addEventListener(evt, function(e){
                callback.call(this,that.standadize(e));
            }  ,false);
        }
        else if(document.attachEvent)
        {
            this.element.attachEvent('on'+evt,function(e){
                callback.call(this,that.standadize(e));
            });
        }
        else{
            this.element['on'+evt]=function(e){
                callback.call(this,that.standadize(e));
            };
        }
    }
}

each : function (object, callback, args) {
	var name,
	i = 0,
	length = object.length,
	isObj = length === undefined || jQuery.isFunction(object);

	if (args) {
		if (isObj) {
			for (name in object) {
				if (callback.apply(object[name], args) === false) {
					break;
				}
			}
		} else {
			for (; i < length; ) {
				if (callback.apply(object[i++], args) === false) {
					break;
				}
			}
		}

		// A special, fast, case for the most common use of each
	} else {
		if (isObj) {
			for (name in object) {
				if (callback.call(object[name], name, object[name]) === false) {
					break;
				}
			}
		} else {
			for (var value = object[0];
				i < length && callback.call(value, i, value) !== false;
				value = object[++i]) {}
		}
	}

	return object;
},

 

使用new创建对象,使用回调函数

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
    callback.call(this, salutation);
}
function foo(salutation) {
    alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
// Alerts "Hi Joe" via `foo`
t.doSomething(foo, 'Hi');

 

 

 

 

你可能感兴趣的:(回调函数)