简体   繁体   中英

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?

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.

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:

克罗克福德在这里有一些很好的解释等。

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

He has several good Javascript articles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM