Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.fn or Function.prototype

Tags:

jquery

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.

like image 919
Chapsterj Avatar asked Jul 30 '26 09:07

Chapsterj


1 Answers

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.

like image 100
Michael Mior Avatar answered Aug 01 '26 00:08

Michael Mior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!