This has been driving me crazy because I can’t find anything on Google. Maybe it’s because I don’t know the right terminology to search right. But this is what I’m trying to do.
I want to create a function that acts like an object. I’m think it’s called a method, though I could be wrong.
Check this out, this is some pseudocode of what I would like it to do.
function myMethod(){
var p = this.getAttribute('x');
var p = p+1;
return p;
}
function otherFunction(){
var q = document.getElementByID('Element').myMethod();
alert(q);
}
So, I can’t get this to work. It keeps saying myMethod() is undefined and not a function.
If you want
myMethodto be available on elements, you’d have to append it to elements’ prototype.The concept of
prototypeis big, but it comes down to the fact that instances of functions have a function available in the way that you describe as ‘like an object’.In this case, any element on the page is an instance of the
Elementfunction. Therefore, any element will have.myMethodavailable, which you can call. (Elementis a function although you don’t really deal with that – the instances are available because you put them there in HTML, so you bypass usingElement.)Second, if you have
var p, then anothervar pdoes not make much sense. Just usep = p + 1, orp++(shortcut for adding one).