ab217
ab217

Reputation: 17180

How JavaScript does OOP?

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?

Upvotes: 2

Views: 325

Answers (5)

jira
jira

Reputation: 3944

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.

Upvotes: 3

Adam
Adam

Reputation: 44969

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:

Upvotes: 3

Frank Schwieterman
Frank Schwieterman

Reputation: 24478

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

He has several good Javascript articles.

Upvotes: 0

orolo
orolo

Reputation: 3951

Crockford has some good explanations here etc.

Upvotes: 2

Related Questions