简体   繁体   English

JavaScript如何做OOP?

[英]How JavaScript does OOP?

I am learning about creating objects in JavaScript. 我正在学习如何在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. 我知道我正在创建一个Person类的实例,但我不知道如何(或者如果)我可以重用该类来创建另一个实例。 What OOP features does JavaScript has? JavaScript有哪些OOP功能? Does it have the same OO features as other languages such as Java, or Ruby? 它是否具有与Java或Ruby等其他语言相同的OO功能? Can someone please explain how JavaScript does OOP? 有人可以解释一下JavaScript如何做OOP吗?

In your example you are not creating an instance of a Person class. 在您的示例中,您不是在创建Person类的实例。 You are creating a variable named 'Person' which contains an anonymous object. 您正在创建一个名为“Person”的变量,其中包含一个匿名对象。

To create a class of type Person you would do: 要创建Person类,您将执行以下操作:

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). 网上有很多javascript文章和教程(书店里有书)。 Go and study them and if you don't understand something specific then post here. 去研究它们,如果你不了解具体的东西,请在这里发布。

JavaScript does not use classes. JavaScript不使用类。 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: 或者您可以使用new关键字:

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/ 查看Oran Looney的文章: http//oranlooney.com/classes-and-objects-javascript/

He has several good Javascript articles. 他有几篇很好的Javascript文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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