JavaScript functions, creating objects, encapsulation, properties and methods, inheriting _javascript tips

Source: Internet
Author: User
Tags function definition inheritance mixed
One, function
From the beginning of contact with JS feel good flexible, everyone's writing is different, such as a function on the N-type
such as: function ShowMsg () {},var showmsg=function () {},showmsg=function () {}
There seems to be no difference, is the same, really the same, we look at the following example
Copy Code code as follows:

///-----------------------------------------------------------------------------------------

-------
function definition: named function (declarative), anonymous function (reference type)
Declarative, defining code before the function execution code is parsed
function T1 () {
Dwn ("T1");
}
T1 ();
function T1 () {
Dwn ("New T1");
}
T1 ();
Reference type, dynamic parsing in function operation
var t1=function () {
Dwn ("New New T1");
}
T1 ();
var t1=function () {
Dwn ("New New New T1");
}
T1 ();
Above output: New t1,new t1,new new t1,new new New T1

It may be thought that it should be output t1,new t1,new newt1,new new New T1, which is not the case and should be understood: statement

, the definition code is parsed before the function execution code
If you go a step further, it should be a scope chain problem, in fact the previous two methods are equivalent to WINDOW.T1, which can be understood as T1 is the window

A public property that was assigned a value of two times, with the last assignment as the final value
The following two methods can be understood to be T1 is a variable, the fourth method of Var removed after the result is still not changed
However, when the fourth method is changed to a declaration such as function T1 () {}, the result becomes the new new new t1,new new New

T1,new New t1,new New T1
The first two can understand why this is the answer and the third one is understandable, but the last output makes me

More tangled, hope to have a master appeared to answer
Also anonymous functions (function () {...}) () In this way, the last bracket is used for parameter input
There is also the Var t1=new function () {.} Such a statement, in fact T1 is already an object of
Cases:
Copy Code code as follows:

var t2 = new Function ()
{
var temp = 100; Private members
This.temp = 200; Public members, these two concepts will be expanded after the 3rd explanation
return temp + this.temp;
}

Alert (typeof (T2)); Object
Alert (T2.constructor ()); 300
In addition, you can use the system built-in function object to build a function, for example:
var t3 = new Function (' var temp = This.temp =; return temp + this.temp; '); This position adds no new results all the same, WHY
Alert (typeof (T3)); function
Alert (t3 ()); 300

Second, create the object
First we understand object-oriented programming (object-oriented Programming,oop), using OOP techniques, often using many

code module, each module provides a specific function, each module is isolated, and even with other modules completely independent
。 This modular programming approach provides a lot of diversity and greatly increases the chances of reusing code. You can give an example to further illustrate this question.

, suppose a high-performance application on your computer is a first-class car. If you use traditional programming skills, this car is
A unit. If you want to improve the car, you must replace the entire unit, send it back to the manufacturer, let the car expert upgrade it, or buy a new

Car. If you use OOP technology, just buy a new engine from the vendor and replace it with the instructions instead of using a hacksaw to cut the body.
But most of the argument is that JavaScript is not a direct object-oriented language, but simulations can do a lot of object-oriented

Words can do things, such as inheritance, polymorphism, encapsulation, JavaScript can be able (not to do, just think)
Copy Code code as follows:

///-----------------------------------------------------------------------------------------

-------
The following three methods of constructing objects
New object, instantiating an object
var a=new Object ();
a.x=1,a.y=2;
Object Direct Quantity
var b={x:1,y:2};
Defining types
function Point (x,y) {//class similar to C #
This.x=x;
This.y=y;
}
var p=new point (1,2); Instantiating classes

The first method is implemented by constructing a method of adding attributes directly to the basic object, the second is similar to the first, and can be considered as the first kind of square

Quick representation of the method
In the third method, you can create multiple objects of the same type based on the "class"

Three, encapsulation of object properties (public and private)
Take an example to illustrate
function List () {
var m_elements=[]; Private members that cannot be accessed outside the object, and if there is no Var declaration here, the m_elements will become global

, such as alert (M_elements[0]), that can be accessed directly from the outside.
Copy Code code as follows:

M_elements=array.apply (m_elements,arguments);
The getter is simulated here and alist.length when used;
Equivalent to the GetName () method: This.length=function () {return m_elements.length;}, when

Alist.length ();
Public property, you can use the "." operator or subscript to access the
this.length={
Valueof:function () {
return m_elements.length;
},
Tostring:function () {
return m_elements.length;
}
}
Public method, this method uses alert (alist) equivalent to alert (alist.tostring ())
This.tostring=function () {
return m_elements.tostring ();
}
Public method
This.add=function () {
M_elements.push.apply (m_elements,arguments);
}
The private method is as follows, and here comes the concept of closure, and then continue to explain
var add=function () or function add ()
//{
M_elements.push.apply (m_elements,arguments);
//}
}
var alist=new List (1,2,3);
Dwn (alist); =alert (Alist.tostring ()), Output 1,2,3
Dwn (alist.length); Output 3
Alist.add (4,5,6);
Dwn (alist); Output 1,2,3,4,5,6
Dwn (alist.length); Output 6

Iv. types of properties and methods
In JavaScript, the object's properties and methods support 4 different types: Private property, the dynamic public

Property (Dynamic public properties), static public Property/prototype property (static publicly owned or stereotype properties),
The static property (either statically or class properties). Private properties are completely inaccessible to the outside world, and can be accessed through the internal getter and

Setter (all analog); Dynamic public properties can be accessed by outsiders, each instance holding a copy, without affecting each other; prototype
property to share a unique replica for each object instance; The Class property is not a property of the instance, only as a property of the class.
Here is an example:
Copy Code code as follows:

///-----------------------------------------------------------------------------------------

-------
Dynamic public type, static public type (prototype property)
function MyClass () {
var p=100; Private property
this.x=10; Dynamic Public Property
}
myclass.prototype.y=20; Static public or prototype property, MyClass for a dynamically-added prototype

With attributes, it will be used for all instantiated objects, and note that prototype is used here, which is a very useful stuff.
To be an advanced JavaScript phase, prototype and closures must be understood and properly applied
myclass.z=30; static property

var a=new myClass ();
Dwn (A.P)//undefined
Dwn (a.x)//10
Dwn (A.Y)//20
a.x=20;
a.y=40;
Dwn (a.x); 20
Dwn (A.Y); 40
Delete (a.x); Delete Object A's properties X
Delete (A.Y); Delete Property Y of Object A
Dwn (a.x); Undefined
Dwn (A.Y); 20 static Public property y is deleted and revert to prototype property y
Dwn (A.Z); Undefined class properties cannot be accessed through an object
Dwn (MYCLASS.Z);

Five, prototype (prototype)
Here only part, prototype and closures are not a few words can be said clearly, if here can give you some enlightenment, it is lucky
Idiom "Suit", where the cat is a prototype, Tiger is the type, can be expressed as: Tiger. Prototype= a cat or

Tiger Prototype=new Cat ()
Because the prototype property shares a unique replica per object instance, all instances are tuned when one of the instances adjusts the value of a stereotype property

This will change when you use this property, which requires attention
The following is the type chain of the prototype relationship:
Copy Code code as follows:

function ClassA () {
}
Classa.prototype=new Object ();
function ClassB () {
}
Classb.prototype=new ClassA ();
function Classc () {
}
Classc.prototype=new ClassB ();
var obj=new classc ();
Dwn (obj instanceof classc); True
Dwn (obj instanceof classb); True
Dwn (obj instanceof ClassA); True
Dwn (obj instanceof Object); True
Point object with default value:
function Point2 (x,y) {
if (x) this.x=x;
if (y) this.y=y;
}
Set the X,y default value of the Point2 object to 0
point2.prototype.x=0;
point2.prototype.y=0;
P1 is a default (0,0) object
var p1=new Point2 (); can be written as Var p1=new Point2 will not go wrong, WHY
P2 Assign Value
var p2=new Point2 (1,2);
Dwn (p1.x+ "," +p1.y); 0,0
Dwn (p2.x+ "," +p2.y); 1,2
After the properties of the Delete object, the prototype property returns to its initialized state:
function CLASSD () {
this.a=100;
this.b=200;
this.c=300
}
Classd.prototype=new CLASSD (); Set the original property of CLASSD to a prototype, including its value
Classd.prototype.reset=function () {//Remove the non-prototype attribute
For (var all in this) {
Delete This[each];
}
}
var d=new classd ();
Dwn (D.A); 100
d.a*=2;
d.b*=2;
d.c*=2;
Dwn (D.A); 200
Dwn (D.B); 400
Dwn (D.C); 600
D.reset (); Delete Non-prototype properties, all back prototypes
Dwn (D.A); 100
Dwn (D.B); 200
Dwn (D.C); 300

Six, Inherit
If all two classes are of the same instance type, then there is a relationship between them, and we put the generalization between the types of the same instance

A relationship is called inheritance. C # and Java have this, the specific understanding will not say.
In JavaScript, inheritance is not directly supported on methods, but as mentioned above, it can be simulated.
The method can be summed up into four kinds: the construction inheritance method, the prototype inheritance method, the instance inheritance method and the copy inheritance method. After mastery, there is also a hybrid

Continuation method, this is what law, is the front four kinds of pick several mixed come ~
The following example comes from the return of the king, which involves the use of Apply,call and some array, and is interested in searching the garden.

A bit
1, construct continuation Law example:
Copy Code code as follows:

Define a collection type
function Collection (size)
{
This.size = function () {return size}; Public methods that can be inherited
}

Collection.prototype.isEmpty = function () {//static method, cannot be inherited
return this.size () = = 0;
}

Defines a ArrayList type that "Inherits" the collection type
function ArrayList ()
{
var m_elements = []; Private members, cannot be inherited
m_elements = array.apply (m_elements, arguments);

ArrayList Type Inheritance Collection
This.base = Collection;
This.base.call (this, m_elements.length);

This.add = function ()
{
Return m_elements.push.apply (m_elements, arguments);
}
This.toarray = function ()
{
return m_elements;
}
}

ArrayList.prototype.toString = function ()
{
Return This.toarray (). toString ();
}
Defines a SortedList type that inherits the ArrayList type
function SortedList ()
{
SortedList Type Inheritance ArrayList
This.base = ArrayList;
This.base.apply (this, arguments);

This.sort = function ()
{
var arr = This.toarray ();
Arr.sort.apply (arr, arguments);
}
}

Construct a ArrayList
var a = new ArrayList (1,2,3);
Dwn (a);
Dwn (A.size ()); A has inherited the size () method from collection
Dwn (A.isempty); But a does not inherit to the IsEmpty () method

Construct a SortedList
var B = new SortedList (3,1,2);
B.add (4,0); b inherits the Add () method from ArrayList
Dwn (B.toarray ()); b inherits the ToArray () method from ArrayList
B.sort (); b the Sort () method implemented by itself
Dwn (B.toarray ());
Dwn (b);
Dwn (B.size ()); b inherits the size () method from collection

2, prototype inheritance Law example:
Copy Code code as follows:

Define a point type
function point (Dimension)
{

This.dimension = dimension;
}

Defines a point2d type, "Inherit" point type
function point2d (x, y)
{
this.x = x;
This.y = y;
}
Point2D.prototype.distance = function ()
{
Return math.sqrt (this.x * this.x + this.y * this.y);
}
Point2d.prototype = new Point (2); POINT2D inherited point.

Defines a Point3D type and also inherits the point type
function Point3D (x, Y, z)
{
this.x = x;
This.y = y;
This.z = Z;
}
Point3d.prototype = new Point (3); Point3D also inherited point.

Construct a Point2d object
var p1 = new point2d (0,0);
Construct a Point3D object
var P2 = new Point3D (0,1,2);

Dwn (p1.dimension);
Dwn (p2.dimension);
Dwn (P1 instanceof point2d); P1 is a point2d
Dwn (P1 instanceof point); P1 is also a point
Dwn (P2 instanceof point); P2 is a point

The above two methods are the most commonly used
3 Examples of example inheritance law:
Before saying this example, talk about the limitations of the structural inheritance law, as follows:
Copy Code code as follows:

function MyDate ()
{
This.base = Date;
This.base.apply (this, arguments);
}
var date = new MyDate ();
alert (date.togmtstring); Undefined,date does not inherit to date type, so there is no toGMTString method

Some methods of the core object cannot be constructed, because the core object does not enter in the constructor like our custom generic object.

Row assignment or initialization operation
What about a prototype inheritance law? As follows:
Copy Code code as follows:

function MyDate () {}
Mydate.prototype=new Date ();
var date=new mydate ();
alert (date.togmtstring); ' [Object] ' is not a Date object and still does not inherit to date type!

Now, replace the instance inheritance method:
Copy Code code as follows:

function MyDate ()
{
var instance = new Date (); Instance is a newly created Date object
Instance.printdate = function () {
document.write ("<p>" +instance.tolocalestring () + "</p>");
}//To Instance Extended PrintDate () method
return instance; Returns the instance as the return value of the constructor
}
var mydate = new MyDate ();
Dwn (Mydate.togmtstring ()); The correct time string was successfully exported, and it appears that MyDate is already an instance of date

, inheriting success
Mydate.printdate (); If you do not have return instance, you will not be able to access the following label because it is a private object's method
4, Copy inheritance Law example:
Copy Code code as follows:

Function.prototype.extends = function (obj)
{
For (var all in obj)
{
This.prototype[each] = Obj[each];
A one-to-one replication of an object's properties, but it is slow and prone to problems
So this "inheritance" approach is generally not recommended for use
}
}
var point2d = function () {
......
}
Point2d.extends (new Point ())
{
......
}

This kind of inheritance law seems to be used very little.
5, Mixed inheritance examples:
Copy Code code as follows:

function point2d (x, y)
{
this.x = x;
This.y = y;
}
function colorpoint2d (x, Y, c)
{
Point2d.call (this, x, y); Here is the constructor inheritance that invokes the constructor of the parent class
As you can see from the previous example, this is equivalent to
THIS.BASE=POINT2D;
This.base.call (This,x,y);
This.color = C;
}
Colorpoint2d.prototype = new point2d (); This is a prototype inheritance that lets colorpoint2d take the Point2d object as a prototype


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.