views:

131

answers:

5

I am learning about creating objects in JavaScript. When I do this ...

var Person = {
   name: "John Doe", 
   sayHi: function() {
   alert("Hi");
   }
};

I know that I am creating an instance of a Person class, but I do not know how (or if) I can reuse that class to create another instance. What OOP features does JavaScript has? Does it have the same OO features as other languages such as Java, or Ruby? Can someone please explain how JavaScript does OOP?

+1  A: 

In your example you are not creating an instance of a Person class. You are creating a variable named 'Person' which contains an anonymous object.

To create a class of type Person you would do:

function Person() {
   this.name = "John Doe", 
   this.sayHi =  function() {
   alert("Hi");
   }
}

var somebody = new Person();

Otherwise I think that your question is too broad and complex. There are many javascript articles and tutorials on the web (and books in the bookstores). Go and study them and if you don't understand something specific then post here.

jira
+2  A: 

Crockford has some good explanations here etc.

orolo
+1, nice reference
RC
+3  A: 

JavaScript does not use classes. It uses prototyping. There are multiple ways of creating new objects.

You could do:

var john = Object.create(Person);

Or you could use the new keyword:

function Person() = {
   this.name = "John Doe", 
   this.sayHi = function() {
     alert("Hi");
   }
};

var john = new Person();

For more information read:

Adam
A: 

Check out Oran Looney's article on this: http://oranlooney.com/classes-and-objects-javascript/

He has several good Javascript articles.

Frank Schwieterman