Previous Blog "09 Classes and modules"--2 classes and constructors
Let's talk about Java class inheritance in JavaScript, and if you've ever experienced Java or other similar strongly-typed object-oriented programming languages, you'll find that the difference between JavaScript and Java classes is The functions in JavaScript are all in a worthwhile form, and there is not much difference between the method and the field. If the attribute is a function, then this property defines a method, otherwise it is just a normal property or "field";
But we can still simulate a class in Java.
If you look at the blog in front of you, you'll know that the class in JavaScript involves three different objects.
1. Constructor Object (any property added to the constructor object is a class field or a class method)
2. Prototype Object (the attribute of the prototype object is inherited by the class's said instance)
3. Instance Objects (all instance objects of a class are independent, attributes defined directly to this instance are not shared by all instance objects)
The steps to define a class in JavaScript can be reduced to three step
1, first define a constructor, and set the initialization of the new object's instance properties
2, to the constructor prototype object Definition instance instance
3. Define class fields and class properties for constructors
Next we encapsulate these three steps into a simple defineclass () function
First do a preparation, define a extend function to copy the attributes and values of one object to another
function Extend (o,p) {
for (Var prop in P) {//Traverse all properties in P
o[prop]=p[prop];//copy properties and values to O
} return
o;
}
And then we'll define a simple class.
function DefineClass (constructor,methods,statics) {
if (methods) extend (constructor.prototype,methods);
if (statics) extend (constructor,statics);
Return constructor
}/
* constructor--The method of a
function methods--instance that sets the property of the instance
, assigning values to the
statics--class attribute in the prototype. Copy to Constructor
* *
With this function encapsulated above, we redefine the range class in the class 09 and--2 classes and constructors
var Simplerange=defindeclass (
function (f,t) {this.f=f;this.t=t},
{
includes:function (x) {return This.from <=x && x<=this.to;,
foreach:function (f) {for
(var x=math.ceil (this.from);x< this.to;x++) f (x)
}}
,
{upto:function (t) {return new Simplerange (O,t)}}
)
It encapsulates a defineclass () function to implement a class similar to Java, where we define a longer class--class Complex.js class that represents a complex number
/* Complex.js This file defines the Complex class, which describes the sum of the plural complex numbers as
real and imaginary numbers, and the description I is the square root of-1/
function Complex (real, imaginary) {
if (isNaN (real) | | | isNaN (IMAGINARY))//Ensure that all two parameters are numeric
throw new TypeError ();
THIS.R = Real; The real part of the plural is
this.i = imaginary; Imaginary part of complex number
}
The instance method of a class is defined as a function Value property of a prototype object, and the method defined here can be inherited by all instances and provide them with shared behavior
Note: You must use the This keyword to access instance properties in these methods
//The following method must also be a tired instantiated object//The current complex number object plus another complex number, and return a new computed value of the plural object Complex.prototype.add =
function (that) {return new Complex (THIS.R + THAT.R, this.i + that.i); The current complex number is multiplied by another complex number and returns a complex number object Complex.prototype.mul = function (that) {return new Complex (THIS.R * that.r-this.i
* THAT.I, THIS.R * that.i + this.i * THAT.R);
}; The modulus of the complex number is calculated as the distance from the far point (0,0) to the complex plane Complex.prototype.mag = function () {return math.sqrt (THIS.R*THIS.R + this.i*this.i);}
;
The negation of complex number Complex.prototype.neg = function () {return new Complex (-THIS.R,-this.i);//returns negative Object};
Converts a complex object to a string Complex.prototype.toString = function () {return "{" + THIS.R + "," + This.i + "}";};
Detects whether the current complex number object is equal to another complex value Complex.prototype.equals = function (that) {"return"!= null &&//that must be defined and cannot be null That.constructor = = Complex &&//that must be Complex instance THIS.R = = THAT.R && this.i = = that.i;//must contain the same value};
Class fields (such as constants) and class methods are directly defined as properties of constructors
It is important to note that the method of the class usually does not use the This keyword, and they manipulate only the parameters
/* This defines some class fields that are helpful for complex numbers, and their names are all uppercase, and are used for table names that are constant
/Complex.zero = new Complex (0,0);
Complex.one = new Complex (1,0);
complex.i = new Complex (0,1);
/* Define a class method that resolves the string format returned by the instance object's ToString () method to a Complex object or throws an error exception/
Complex.parse = function (s) {
try {
var m = complex._format.exec (s); Use regular expressions to match return
new Complex (parsefloat (m[1]), parsefloat (m[2));
} catch (x) {
throw new TypeError ("Can ' t Parse '" + S + "' as a complex number.");
}
;
Defines a "private field" of a class that uses the//underscore prefix in Complex.parse () to
indicate that it is used internally, not part of the public API
Complex._format =/^\{([^,]+), ([ ^}]+)\}$/;
Above is the whole process of defining a class, if you need to add instance methods, you can continue to add on the prototype object, where we use constructors, instance fields, instance methods, class fields, class methods, the following class to use this class
var c = new Complex (2,3)//using the constructor to instantiate the object
var d = new Complex (C.I,C.R)//is also an instantiated object, except for the properties of Object C
C.add (d). ToString () C2/>//=> ' {5,5} ': the instance's ToString () method
//The following is a slightly more complex use of the class method and the Class field
Complex.parse (c.tostring ()).// Converts the Instance object C to String
Add (C.neg ()).//Plus the object itself's negative
equals (Complex.zero)//result is always "0", so return True forever
Although JavaScript can simulate Java-style class members, many of the most important features in Java are not emulated in JavaScript
1. For Java instance methods, instance fields can be used as local variables without the use of the This keyword to refer to them, but JavaScript is not able to simulate this feature, but you can use the WITH statement to approximate the implementation
Complex.prototype.tostring=function () {
with [this] {return
' {' +r+ ', ' +i+ '}}
}}
2. In Java, you can use the Final declaration field constants, and you can declare fields and methods as private, to indicate that they are private members and not visible outside of the class, and that they are not in JavaScript. But private properties in JavaScript can also be simulated with local variables in the closure.
I expect you to read the next post. "Class 09 and modules"--4: Extensions of Classes