Reputation: 2774
I want to create a function that will behave as method to all elements like JQuery methods. for exemple:
function myFunction(p1,p2){
//things
}
element.myFunction(p1,p2);
I think that Object.prototype is not allowed . Any idea ?? plz I am new to OOP in javascript. Thx
Upvotes: 2
Views: 130
Reputation: 6955
You can do something like this:
$ = function (element){
return {
myFunction: function (p1,p2){
alert(element.id + " " + (p1 + p2));
//do stuff with element and p1 and p2
}
}
}
$(document.getElementById("test")).myFunction(50,80)
This returns an object with that function in it. It uses lexical scoping to hold onto a reference to the element you gave it while still being able to pass in new parameters into myFunction
Here is a jsfiddle with this in action! http://jsfiddle.net/vnbQU/
Upvotes: 1
Reputation: 204718
myFunction.call(element, p1, p2);
will call myFunction(p1, p2)
with this
bound to element
, similar to if myFunction
were in element.prototype
and were called through element.myFunction(p1, p2)
.
Upvotes: 3