tags:

views:

89

answers:

3

I'm hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so that I can just do

var vehicle = new Vehicle(el);
var model = vehicle->getModel();

These functions would read the HTML and get and manage the elements on the page. I'm current doing a setup like...

var model = function () {
 return {
  getName: function () {

  },
  getVehicleCount: function () {

  },
  incrementCount: function (id) {
   console.log(x);
  }
 }
}();

I'm still learning classes in Javascript... I'd like to be able to pass the class a node for the element all of the methods will use, but I'm not sure I'm doing this right...

A: 

There is nothing like classes in JavaScript. JavaScripts inheritance works with prototypes. You can take a look at base2, which mimics class-like behaviour in JavaScript.

elusive
+2  A: 

There is no such thing as a class in Javascript, instead everything in Javascript is an object.

To create a new object you define a function that uses the "this" keyword in it.

function Foo (id) {
    this.id = id;
}

var foo1 = new Foo(1);
var foo2 = new Foo(2);

However, these "objects" have no methods. To add methods, you need to define a prototype.

Foo.prototype = {
    getId: function () {
        return this.id;
    }
}

This new "getId" function will be usable by all Foo objects. However, as was stated, there are no classes in javascript and as such there are other constructs you will use in order to produce different results.

I highly recommend the videos by Douglas Crockford in which he explains much of the javascript OO nature. The talks can be found here:

http://developer.yahoo.com/yui/theater/

Douglas Crockford — The JavaScript Programming Language

Douglas Crockford — Advanced JavaScript

Those will give you a basic understanding of the structure of javascript and should help the transition from classical to functional programming.

Richard Cook
A: 

See this post. Very helpful.

jason m