How to change the context of a function in javascript

前端 未结 6 1735
醉梦人生
醉梦人生 2020-12-13 19:24

I\'m trying to understand why in javascript, you might want to change the context of a function. I\'m looking for a real world example or something which will help me unders

6条回答
  •  悲&欢浪女
    2020-12-13 19:57

    jQuery makes use of it to good effect:

    $('a').each(function() {
        // "this" is an a element - very useful
    });
    

    The actual jQuery code looks like this:

    for ( name in object ) {
        if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
            break;
        }
    }
    

    If it just did callback( name, object[ name ] ) then this wouldn't be set to the current object in your iterator and you'd have to use the parameter instead. Basically it just makes things easier.

提交回复
热议问题