2

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?

3
  • 1
    @orolo, youshould transform your comment into an answer, it's good imho. Commented Oct 8, 2010 at 20:45
  • 2
    Actually, the Person in you're example is a single object, not a class. Classes are usually defined as functions (that then get newed up). Try checking out mckoss.com/jscript/object.htm for an explanation of class inheritance, etc. Commented Oct 8, 2010 at 20:47
  • @Cameron: +1. I was going to suggest that link in an answer. I like going back to that article for Object behavior. Commented Oct 8, 2010 at 20:56

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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:

Comments

2

Crockford has some good explanations here etc.

Comments

1

There are several good online sources to read:

  1. McKoss
  2. Crockford
  3. JavaScript Tutors
  4. Looney
  5. SitePoint

Comments

0

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

He has several good Javascript articles.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.