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
just to offer up some variety. ds.oop is a nice way to declare classes with constructors in javascript. It supports every possible type of inheritance (Including 1 type that even c# does not support) as well as Interfaces which is nice.
http://www.jsoops.net/ is quite good for oop in Js. If provide private, protected, public variable and function, and also Inheritance feature. Example Code:
In most cases you have to somehow declare the property you need before you can call a method that passes in this information. If you do not have to initially set a property you can just call a method within the object like so. Probably not the most pretty way of doing this but this still works.
While using Blixt's great template from above, I found out that it doesn't work well with multi-level inheritance (MyGrandChildClass extending MyChildClass extending MyClass) – it cycles on calling first parent's constructor over and over. So here is a simple workaround – if you need multi-level inheritance, instead of using
this.constructor.super.call(this, surName);
usechainSuper(this).call(this, surName);
with the chain function defined like this:It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming).
lunched-dan was closer but the example didn't work in jsFiddle.
This example creates a private constructor function that only runs during the creation of the object.
If you wanted to assign public properties then the constructor could be defined as such:
Yes, you can define a constructor inside a class declaration like this: