Can JavaScript classes/objects have constructors? How are they created?
相关问题
- Is there a limit to how many levels you can nest i
- how to define constructor for Python's new Nam
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
They do if you use Typescript - open source from MicroSoft :-)
Typescript lets you 'fake' OO constructs that are compiled into javascript constructs. If you're starting a large project it may save you a lot of time and it just reached milestone 1.0 version.
http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf
The above code gets 'compiled' to :
Here's a template I sometimes use for OOP-similar behavior in JavaScript. As you can see, you can simulate private (both static and instance) members using closures. What
new MyClass()
will return is an object with only the properties assigned to thethis
object and in theprototype
object of the "class."I've been asked about inheritance using this pattern, so here goes:
And an example to use it all:
As you can see, the classes correctly interact with each other (they share the static id from
MyClass
, theannounce
method uses the correctget_name
method, etc.)One thing to note is the need to shadow instance properties. You can actually make the
inherit
function go through all instance properties (usinghasOwnProperty
) that are functions, and automagically add asuper_<method name>
property. This would let you callthis.super_get_name()
instead of storing it in a temporary value and calling it bound usingcall
.For methods on the prototype you don't need to worry about the above though, if you want to access the super class' prototype methods, you can just call
this.constructor.super.prototype.methodName
. If you want to make it less verbose you can of course add convenience properties. :)Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:
Using prototypes:
Hiding "color" (somewhat resembles a private member variable):
Usage:
The point of the constructor property is to provide some way of pretending JavaScript has classes. One of the things you cannot usefully do is change an object's constructor after it's been created. It's complicated.
I wrote a fairly comprehensive piece on it a few years ago: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html
In JavaScript the invocation type defines the behaviour of the function:
func()
obj.func()
new func()
func.call()
orfunc.apply()
The function is invoked as a constructor when calling using
new
operator:Any instance or prototype object in JavaScript have a property
constructor
, which refers to the constructor function.Check this post about constructor property.