Page 1 of 1

OO Javascript help

Posted: Fri Jun 13, 2008 3:35 pm
by incubusor
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.

Code so far...

Code: Select all

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
}
 

Re: OO Javascript help

Posted: Fri Jun 13, 2008 4:02 pm
by VladSun

Re: OO Javascript help

Posted: Fri Jun 13, 2008 5:41 pm
by incubusor
Interesting read, however, I'm trying to avoid using JQuery or any other framework. I was starting from scratch to figure this out.

Re: OO Javascript help

Posted: Fri Jun 13, 2008 6:51 pm
by Eran
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.

Javascript uses prototypical inheritance instead of class based inheritance. You can read a little about it here - http://phrogz.net/js/Classes/ExtendingJ ... asses.html

Re: OO Javascript help

Posted: Fri Jun 13, 2008 6:53 pm
by VladSun
You may look to the jquery JS source to get the idea.

Re: OO Javascript help

Posted: Fri Jun 13, 2008 10:54 pm
by Kieran Huggins
If you just want to make your own classes with methods, you can do so like this:

Code: Select all

// 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>'