How to build a "class" (with properties and methods) upon which will be created a lot of instances?
标签:
javascript
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You could also use a anonymous function to simulate private and public
I don't like this pattern though. The underscore warning _myVariable should be enough to keep users of your lib from using those variables / methods. I used it allot when I first discovered it because of my Java background.. It makes it difficult to work with prototype inheritance and can cause memory leaks.
The approach to object orientation most native to JavaScript is to use prototypal inheritance, but many other patterns exist, including pseudoclassical inheritance, which mimics the class-based inheritance pattern in languages like C and Java. Douglas Crockford has written and spoken on the subject and provides some very good explanations of each. Take a look at these articles:
Prototypal Inheritance in JavaScript
Classical Inheritance in JavaScript
By using an anonymous self-executing function, you can allow for public and private attributes/methods.
This is the pattern I like the most:
Learned about it from the comments here and this article.
The modern way is to use
class
, as introduced in ES6.The above example provides an equivalent interface to the original examples from 2010.
Original answer from 2010:
In "modern" JavaScript, there are three popular methods for defining objects.
The first method is the classic method and is still popular because of its simplicity; however, it is discouraged by MDC in favor of the second method because of the inefficiency of having to redefine each function every time an instance of the object is created.
The second method is a variation of and can be used interchangeably with the first. It is also useful for adding new methods to existing objects via the
prototype
property. Private members and methods are not possible in this form.The third method is to use the module pattern, which makes it possible to instantiate objects without having to use the
new
operator.Note that in the first and third methods, you can use private access members and methods. But be aware that to use
this
within private methods some must happen.JavaScript does not use classes in the same way as Java, C++ or the like.
One way to achieve your effect is to define a function in which the this keyword is used--accessing members roughly as you would in Java. Then, use the new keyword in calling this function to create an object.
http://www.phpied.com/3-ways-to-define-a-javascript-class/