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
I found this tutorial very useful. This approach is used by most of jQuery plug-ins.
http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=OVYAQL_TDpK
Now ,
Example here: http://jsfiddle.net/FZ5nC/
Try this template:
You must adjust your namespace if you are defining a static class:
Example class:
Example instantiation:
Notice functions are defined as A.B = function A_B(). This is to make your script easier to debug. Open Chrome's Inspect Element panel, run this script, and expand the debug backtrace:
This is a constructor:
When you do
MyClass
is executed, and a new object is returned of that class.Here we need to notice one point in java script, it is a class-less language however,we can achieve it by using functions in java script. The most common way to achieve this we need to create a function in java script and use new keyword to create an object and use this keyword to define property and methods.Below is the example.
Maybe it's gotten a little simpler, but below is what I've come up with now in 2017:
In using the class above, I have the following:
As you can see, the constructor takes in two parameters, and we set the object's properties. We also alter the object's color and shape by using the
setter
functions, and prove that its change remained upon callinggetInfo()
after these changes.A bit late, but I hope this helps. I've tested this with a
mocha
unit-testing, and it's working well.This pattern has served me well. With this pattern, you create classes in separate files, load them into your overall app "as needed".