Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery work : I get "Cannot set property xxx of undefined" when trying a similar prototype thing?

How does JQuery handle the "Cannot set property xxx of undefined" issue?" If I have:

function Foo() {
   Foo.fn = Foo.prototype;
}

Then I have an extension JavaScript file with this code:

(function(foo) {
   foo.fn.myPlugin = function() {
       //return something here
   };
})(Foo);

I get an error that says "Cannot set property myPlugin of undefined." Funny enough if I just copy the plugin code into FireBug or Chrome and execute it in the console, it works fine and attaches and works as expected like:

foo.myPlugin();

I'm guessing my problem either comes from the timing of the browser loading the document, or the fact that my existing object isn't inside of it's own namespace. I'm wondering if this only works when you define a class using the var syntax??

I don't know...from what I understand...either should work.

like image 234
farina Avatar asked Nov 28 '25 16:11

farina


1 Answers

function Baz() {
   return this;
}
Baz.prototype.fn = Baz.prototype;
var Foo = new Baz();
Baz = null;
(function(Bar) {
   Bar.fn.myPlugin = function() {
       return "test";
   };
})(Foo);
Foo.myPlugin(); //returns test

This works, and leaves Baz assignable. Not sure if that is how jQuery does it or not.

like image 95
schizodactyl Avatar answered Dec 01 '25 11:12

schizodactyl



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!