0

i've created a new js function like this

Object.prototype.testFn = function(){
    s=this;
    alert(s);
    }
a='word';           
a.testFn(); 

i'ts working as well, but, when i use jQuery sdk, then i call jQuery live, my testFn function is called repeatedly. and sometimes, the whole script is not working...

theHack
  • 1,938
  • 9
  • 26
  • 33
  • 1
    The solution is simple: Don't extend `Object.prototype`. It breaks jQuery and is bad style anyway. – Felix Kling Apr 06 '11 at 09:24
  • @Felix Kling: so, hows the way to build a js function within jQuery sdk? – theHack Apr 06 '11 at 09:27
  • Can't you just create a global function with `function testFn() {}`? – vhallac Apr 06 '11 at 09:29
  • 1
    @AfrigAminuddin: Not really sure what you mean with that. Just define your functions normally. jQuery is only JavaScript. Or do you want to create a plugin for jQuery? A function that can be called on a jQuery object, like `$('selector').yourFunction()` ? Please clarify. – Felix Kling Apr 06 '11 at 09:30
  • @Dysaster:ya, it can be... but, i want to build a function like jQuery plugin does... – theHack Apr 06 '11 at 09:31
  • @Felix Kling: ya you're right, i will... – theHack Apr 06 '11 at 09:32
  • not sure what exactly you would like to achieve with this function. Would be helpful to answer if you could elaborate the big picture. – Anil Namde Apr 06 '11 at 09:33

1 Answers1

1

As said in my comment, extending Object.prototype is a bad idea. It most likely will break other libraries.

There is no special way to define functions when you are using jQuery. It is simply:

function myFunction(obj) {
    // manipulate obj
}

But as you mention jQuery, mayby you want to create a plugin, the basic structure is:

jQuery.fn.myPlugin = function() {

  // Do your awesome plugin stuff here

};

You have to extend jQuery.fn.

How to create a plugin is very well explained in the Plugins/Authoring tutorial.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • `this` on this function refers to DOM Object, and the object is must be the jQuery object, unlike my function above, `this` refers to `a` object as a string – theHack Apr 06 '11 at 09:39
  • If you are using jQuery and want to define your own function to manipulate DOM Objects in some way I definitely recommend extending jQuery as explained above. You get all the benefit from Sizzle (jQuery's selector engine) and the other jQuery perks. – EMMERICH Apr 06 '11 at 09:42
  • @EMMERICH: what should i do when the object is not DOM object, my `a` object is a string, i want to manipulate this string... – theHack Apr 06 '11 at 09:47
  • @AfrigAminuddin: Well, I don't really know what you want. If you want to extend every object, then it is not related to jQuery at all and I wonder why you mention it. That you should not extend `Object.prototype` still holds. Define a function instead which accepts the object as first argument. – Felix Kling Apr 06 '11 at 09:47