0

I have three simple Javascript object definitions in my HTML page. The first one works but the others seems to cause an error on the page. I am interested to learn to see which way is the most common way to declare an object in Javascript and which way is the best way to declare an object in Javascript. I have used C++, Java, and the .NET frame work and there seems to be a standard way of declaring objects in these types of OOP languages.

I would like to find a way that is standard to declare the objects so that my code is standard across all of the web pages that I work on. That is I would like to have my methods and properties all declared in the object at declaration type and not so much as just add them in as one goes which I think is possible for the most part from what I have seen in the code.

I also declared an empty object which I think is correct.

 var Ball = {}; //Shouldn't this be an empty object

Question: I think that I am not completely certain what object means in this sense and how it should be used in Javascript objects?

For example: In Java or C++ the new operator creates a new instance of the object. Like below.

 class PPP {
    int temp;
 }

 PPP testobject = new PPP(); 

The above is how I would create an instance of class PPP in Java but how would this be done in Javascript seems different because I think that the Object keyword is throwing me off here and there is some reason I read (not sure where) that Javascript is somewhat different in that everything is a function or something?????

Code:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<body>
<p>Test</p>

<script>
var myCar = new Object();

    myCar.make = "Ford";
    myCar.model = "Mustang";
    myCar.year = 1969;

var myPickup = new Object();

    myPickup.make = "Ford";
    myPickup.model = "Mustang";
    myPickup.year = 1969;

var Ball = {}; //Shouldn't this be an empty object

var testObj = new Object();
    testObj.tst = "test";

var AA = new testObj();
var BB = new testObj();   

</script>   

</body>
</html>

Error:

The below two object declarations are causing me an error which I am not completely certain as to why? I created the object just like the myCar and created one property and then created tow new objects and I receive an error that is listed below.

    var AA = new testObj();
    var BB = new testObj();  

    Uncaught TypeError: object is not a function 

More Code:

The following is object code as well but it has a function objectName() as the declaration which i think is extremely confusing for me. Could this be built with

Car c = new Object();
c.desc = somevalue;
c.color = another value;
c.getInfo = function getInfo() {
      someCodeGoesHere;
}

But some where I saw that to declare a function outside of the class you have to do it like this. So I think that the prototype work is used for most things.

  Car.prototype.getInfo = function() {
     return 'A ' + this.color + ' ' + this.desc + '.';
  };

How it was defined in the example I saw.

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() 
    {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

var car = new Car('Porsche boxter');
car.color = "blue";
alert(car.getInfo()); 
  • As some answers pointed out; you can use constructor functions for your "class" definition and define instance specific members in there then define shared members on the prototype. For a more detailed explanation you can check out this answer: http://stackoverflow.com/a/16063711/1641941 – HMR Apr 02 '14 at 01:23

3 Answers3

1

Contrary to what you might think, Object is not a plain object - it's a function. That's easy to check:

console.log(typeof Object); // 'function'

When used in conjuction with new word, this function is used to build objects by a common template, defined in Object function. For example:

var myCar = new Object(); // function `Object`, build me an object!

Then you add some new properties to that object in these lines:

myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

It's all fine - except that you can do it one step, which should be a little bit faster and more readable:

var myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};

But the point is that the object has been built with a specific function - its constructor. You can create your own constructor functions:

function Pickup() {
  this.make  = 'Ford';
  this.model = 'Mustang';
  this.year  = 1969;
}

... then use it to build objects:

var myPickup = new Pickup();
console.log(myPickup.make); // 'Ford';

Note the difference between console.log(myCar) and console.log(myPickup): in the first case, it's some plain Object, in the second, it's Pickup.


Now to the error you have: see, new keyword is designed to be used with function. So this...

var testObj = new Object();
    testObj.tst = "test";

var AA = new testObj();

... is just wrong. I've already shown how you can create your own constructor function, but there's another way - you can create some prototype object, then use it as a template for infinite (sort of) copies. Like this:

var carPrototype = {
  make: 'ZAZ',
  model: 'Zaporotzets',
  year: '2014'  
};

var myOtherCar = Object.create(carPrototype);
var yetAnotherCar = Object.create(carPrototype);

console.log(myOtherCar === yetAnotherCar); // false
console.log(myOtherCar.make === yetAnotherCar.make); // true

myOtherCar.make = 'Ferrari';
myOtherCar.model = 'Testarossa';
console.log(myOtherCar); // Object { make="Ferrari", model="Testarossa", year="2014"}
console.log(yetAnotherCar); // Object { make="ZAZ", model="Zaporotzets", year="2014"}

See? These are two different - and independent - objects created by a single template. You can modify properties of those separately, but by default they all have some values defined in the prototype object - the one that was used as Object.create param.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • So I can add methods or properties two one after it has been created which would not affect the other object that was created. So in reality one object could have 2 properties and 5 methods while another could have 3 properties and 10 methods. –  Apr 01 '14 at 18:48
  • Yes. But you actually can prevent this 'property creep' from happening with `Object.defineProperty`. ) – raina77ow Apr 01 '14 at 18:51
  • What is property creep exactly and how is Object.defineProperty used? –  Apr 01 '14 at 18:53
  • Property creep => making more properties on the object that's originally designed. And here's a [useful tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) on `Object.defineProperty` (I'd suggest checking `Object.freeze()` and `Object.seal()` too). – raina77ow Apr 01 '14 at 18:54
0

I understand that this is the way you really want to do it:

function testObj() {
    this.tst = "test";
}
var AA = new testObj();
console.log(AA.tst); // "test"
console.log(typeof AA); // object, not a function ;)
  • No, I am trying to find out that in general if I were to create a class in Javascript which would be the most readable for later reference and what is the best way. –  Apr 01 '14 at 17:45
0

There are many patterns in JavaScript. Two common ones are object literals and Constructors, and note that a Constructor is just a function, and by convention, starts with an upper case letter, such as Animal or Car.

The simplest is, as you have:

var obj = {};

or

var obj = { foo: 123, bar: 3.14, wah: "hello", lah: function() { } };

and with Constructor:

function Car(name) {
    this.name = name;
    this.showName = function() {
        console.log("my name is", this.name);
    }
}

var lulu = new Car("lulu"), woowoo = new Car("woowoo");

lulu.showName();

you can read more about the Module Pattern in http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

and the Constructor Pattern in http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • On the first example you just add in properties when you need them. So if it was a class of Animals and I need to add in a growl property you would just enter that at some point in the code correct? But the second way is all internal. –  Apr 01 '14 at 17:48
  • 1
    you can always append properties to an object by using `obj.wahlah = something;` Typically, if you use the Constructor pattern, you have everything defined in the class. – nonopolarity Apr 01 '14 at 17:52
  • Is the function Car(name) { code here } ---- does that appear in the variable declaration or does that appear after the class? –  Apr 01 '14 at 18:15
  • the function `Car` is actually the "class definition". It is the blue print of how your object should be. The class definition is a blue print, like a building's blue print, and using it, your object can be created according to the blue print – nonopolarity Apr 01 '14 at 18:35