Chapsterj
Chapsterj

Reputation: 6625

$.fn or Function.prototype

I'm trying to get this to work.

$.fn.createDelegate = function(scope){
var fn = this;
   return function() {
       return fn.apply(scope, arguments);
   }
 }

The below version works but I thought they were both the same. The first being a shorthand way of writing the second. Or maybe I have gotten the idea incorrect.

Function.prototype.createDelegate = function(scope){
var fn = this;
   return function() {

       return fn.apply(scope, arguments);
   }
 }

When I call the first like this: var delegate = this.myMethod.createDelegate(this); setTimeout(delegate, 3000);

It says not a function. The second method with Function.prototype works. Can someone explain why and set me straight.

Also would it be best to have this as a small plugin so it doesn't get overwritten thought a large project.

Upvotes: 3

Views: 1899

Answers (2)

lonesomeday
lonesomeday

Reputation: 237975

$.fn is a shorthand for jQuery.prototype, used for adding methods to jQuery selections. It is not a shorthand for Function.prototype. You can, however, use the built in jQuery function $.proxy which will do what you want, I think.

You would do something like this:

var delegate = $.proxy(this.myMethod, this);
var delegate = $.proxy(this, 'myMethod'); // slightly briefer but less explicit syntax

Upvotes: 3

Michael Mior
Michael Mior

Reputation: 28752

Assigning to $.fn will give you a function on the jQuery object. jQuery intentionally doesn't touch prototypes of native objects (which is what the second example does). If that style of code appeals you, then you may want to look at Prototype.

Upvotes: 3

Related Questions