Object Oriented Javascript

I'll be honest, I don't write a lot of object oriented Javascript code. It seems like every time I do, I have to look up how to do it correctly and there are lots of different ways to write object oriented code in javascript. I found a Nefarious Designs article to be a good reference.

Many people suggestion using prototype to add functions to an object, but that seems less like other languages, so I prefer the following style.

Whenever you think about using a global variable or trying to pass something by reference, it might be time to setup an object.

Note: In Javascript, objects are passed by reference while strings and integers are not.

function circle(radius)
{
  var radius = radius;
  var getArea = function()
  {
    return (this.radius * this.radius) * Math.PI;
  };
  return true;
}

Here's another way. I'm not sure which I prefer.

function circle(radius)
{
  this.radius = radius;
  this.getArea = function()
  {
    return (this.radius * this.radius) * Math.PI;
  };
  return true;
}
comments powered by Disqus
javascript/object_oriented_javascript.txt · Last modified: 2020/06/01 22:53 (external edit)