Hey, Javascript newbie here. I have been trying to figure out how JQuery, Prototype and other frameworks go about making JS more OO like. I understand the $ function, but can't figure out how to add methods to it. I'm starting off with a simple example.
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
Element.extend {
hide: function() {
this.style.display = 'none';
},
show: function() {
this.style.display = '';
}
}
window.onload = function() {
$('myTestElement').hide(); //isn't working
}
You are using OO syntax that is not a part of Javascript natural syntax. You may have seen it used in the frameworks you mentioned, but it is only available there since they add their own custom syntax.
// define the class
function Bookmark(){
// define class variables
var name = null
var uri = null
// define a class method
function print_link(){
return '<a href="' + this.uri + '>' + this.name + '</a>'
}
}
// then use it
google = new Bookmark
google.name = "Google"
google.uri = 'http://google.com'
google.print_link() // returns '<a href="http://google.com">Google</a>'