Home  >  Article  >  Web Front-end  >  JavaScript functions, object creation, encapsulation, properties and methods, inheritance_javascript skills

JavaScript functions, object creation, encapsulation, properties and methods, inheritance_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:09:511116browse

1. Function
I feel so flexible from the beginning when I came into contact with js. Everyone’s way of writing is different. For example, there are N ways of writing a function
For example: function showMsg(){}, var showMsg=function( ){}, showMsg=function(){}
There seems to be no difference. They are all the same. Are they really the same? Take a look at the example below

Copy code The code is as follows:

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

-------
//Function definition: named function (declarative), anonymous function (reference Formula)
//Declarative, the definition code is parsed before the function execution code
function t1(){
dwn("t1");
}
t1();
function t1(){
dwn("new t1");
}
t1();
//Reference type, dynamically parsed during function operation
var t1=function (){
dwn("new new t1");
}
t1();
var t1=function(){
dwn("new new new t1");
}
t1();
//The above output: new t1, new t1, new new t1, new new new t1

Maybe it should be output t1, new t1, new newt1, new new new t1, but the result is not like this. You should understand this sentence: declaration

formula, the definition code is parsed before the function execution code
If you go one step deeper, it should be said Scope chain problem. In fact, the first two methods are equivalent to window.t1. It can be understood that t1 is a public property of window. It is assigned two values, and the last assignment is the final value. >The latter two methods can be understood as t1 is a variable, and the result of the fourth method after removing the var will still not change
However, when the fourth method is changed to a statement like function t1(){} When formula, the result becomes new new new t1,new new new

t1,new new t1,new new t1
According to my understanding, the first two can well understand why this answer is, The third one is also understandable, but the last output makes me more confused than

. I hope there are experts who can answer it
In addition, there are anonymous functions such as (function(){...})() The way of writing, the last bracket is used for parameter input
and there is a statement like var t1=new function(){..}. In fact, t1 is already an object
Example:



Copy code The code is as follows: var t2 = new function()
{
var temp = 100; //Private members
this.temp = 200; //Public members, these two concepts will be explained in the third point and later
return temp this.temp;
}

alert (typeof(t2)); //object
alert(t2.constructor()); //300
In addition, there is also the use of system built-in function objects to construct a function, for example:
var t3 = new Function('var temp = 100; this.temp = 200; return temp this.temp;'); //The result is the same whether new is added or not at this position, WHY
alert(typeof(t3)) ; //function
alert(t3()); //300


Second, create objects
First we understand Object-Oriented Programming (OOP), use OOP technology often uses many

code modules. Each module provides specific functions. Each module is isolated or even completely independent from other modules
. This modular programming approach provides great diversity and greatly increases opportunities for code reuse. To further illustrate this problem

, suppose that a high-performance application on your computer is a first-class racing car. Using traditional programming techniques, the car would be
a single unit. If you want to improve the car, you have to replace the entire unit, send it back to the manufacturer and have a car expert upgrade it, or buy a new

car. If you use OOP technology, you only need to buy a new engine from the manufacturer and replace it yourself according to the instructions, instead of cutting the car body with a hacksaw.
But most of the argument is that JavaScript is not a direct object-oriented language, but through simulation it can do many things that object-oriented languages ​​​​

can do, such as inheritance, polymorphism, and encapsulation , JavaScript can do it (it’s not impossible, I just can’t think of it)



Copy code The code is as follows: ///------------------------------------------------- ---------------------------------------------
- ------
//The following three methods of constructing objects
//new Object, instantiate an Object
var a=new Object();
a.x=1,a.y= 2;
//Object direct quantity
var b={x:1,y:2};
//Definition type
function Point(x,y){ //Similar to C# Class
this.x=x;
this.y=y;
}
var p=new Point(1,2); //Instantiate class


The first method is implemented by constructing a basic object and directly adding attributes. The second method is similar to the first method and can be regarded as a shortcut representation of the first method


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

3. Encapsulation of object attributes (public and private)
Illustration with examples
function List (){
var m_elements=[]; //Private members cannot be accessed outside the object. If there is no var declaration here, m_elements will become a global variable

, so that the outside can directly Accessed, such as alert(m_elements[0])
Copy code The code is as follows:

m_elements=Array.apply(m_elements,arguments);
//Simulate getter here, when used alist.length;
//Equivalent to getName() method: this.length=function(){return m_elements .length;}, when used

alist.length();
//Public properties can be accessed through the "." operator or subscript
this.length={
valueOf:function(){
return m_elements.length;
},
toString:function(){
return m_elements.length;
}
}
//Public Method, this method uses alert(alist) which is equivalent to alert(alist.toString())
this.toString=function(){
return m_elements.toString();
}
// Public method
this.add=function(){
m_elements.push.apply(m_elements,arguments);
}
//Private method is in the following form, which involves the concept of closure, continue Let’s continue the explanation
//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

4. Types of properties and methods
In JavaScript, object properties and methods support 4 different types: private property (private property), dynamic public

property (dynamic public property), static public property/prototype property (static public property or prototype property),
static property (static property or class property). Private properties are completely inaccessible to the outside world and can be accessed through internal getters and

setters (both are simulations); dynamic public properties can be accessed by the outside world, and each object instance holds a copy and will not affect each other; Prototype
attributes share a unique copy with each object instance; class attributes are not used as attributes of the instance, only as attributes of the class.
The following is an example:
Copy code The code is 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 property or prototype property, dynamically adds

properties to the prototype of myClass, which will apply to all instantiated objects. Note that prototype is used here, which is a very useful thing
//To become an advanced JavaScript stage, prototype and closure must be understood and appropriately 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 the attribute x of object a
delete( a.y); //Delete the attribute y of object a
dwn(a.x); //undefined
dwn(a.y); //20 The static public attribute y is restored to the prototype attribute y
dwn( after being deleted a.z); //undefined class attributes cannot be accessed through objects
dwn(myClass.z);

5. Prototype (prototype)
Only part of it is discussed here, prototype and closure are both It’s not something that can be explained clearly in just a few words. If this can give you some enlightenment, you’re lucky
As the idiom “photograph a cat and draw a tiger”, the cat here is the prototype, and the tiger is the type, which can be expressed as: tiger.prototype=someone cat or

tiger.prototype=new cat()
Because prototype properties share a unique copy per object instance, when one of the instances adjusts the value of a prototype property, all instances adjust

Every time you use this attribute, you need to pay attention to this
The following is the type chain of the prototype relationship:
Copy codeThe code is 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 of the Point2 object , the default value of y is 0
Point2.prototype.x=0;
Point2.prototype.y=0;
//p1 is a default (0,0) object
var p1= new Point2(); //You can write var p1=new Point2 without error, WHY
//P2 assignment
var p2=new Point2(1,2);
dwn(p1.x " ," p1.y); //0,0
dwn(p2.x "," p2.y); //1,2
After deleting the properties of the object, the prototype properties will return to the initialized state :
function ClassD(){
this.a=100;
this.b=200;
this.c=300
}
ClassD.prototype=new ClassD() ; //Set the original properties of ClassD as prototypes, including their values ​​
ClassD.prototype.reset=function(){ //Delete non-prototype properties
for (var each 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 attributes and return all prototypes
dwn(d.a); //100
dwn(d.b); //200
dwn(d.c); //300

6. Inheritance
If two classes are of the same instance type, then there is a certain relationship between them. We generalize the types of the same instance

The relationship is called inheritance. This is available in both C# and JAVA, so I won’t go into the specific understanding.
In JavaScript, inheritance is not directly supported from methods, but as mentioned before, it can be simulated.
Methods can be summarized into four types: construction inheritance, prototype inheritance, instance inheritance and copy inheritance. Law. After mastering it, there is also a mixed continuation

method. What is this method? It is to choose a few of the previous four and mix them~
The following example comes from Return of the King, which involves apply, call and some If you are interested in the usage of Array, you can search for

in the garden
1. Example of construction continuation method:
Copy code The code is as follows:

//Define a Collection type
function Collection(size)
{
this.size = function(){return size} ; //Public method, can be inherited
}

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

//Define an ArrayList type, which "inherits" the Collection type
function ArrayList()
{
var m_elements = []; //Private members, cannot be Inherit
m_elements = Array.apply(m_elements, arguments);

//ArrayList type inherits 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();
}
//Define a SortedList type, which inherits the ArrayList type
function SortedList()
{
//The SortedList type inherits ArrayList
this.base = ArrayList;
this .base.apply(this, arguments);

this.sort = function()
{
var arr = this.toArray();
arr.sort.apply(arr, arguments);
}
}

//Construct an ArrayList
var a = new ArrayList(1,2,3);
dwn(a);
dwn (a.size()); //a inherits the size() method from Collection
dwn(a.isEmpty); //but a does not inherit the isEmpty() method

//Construct one SortedList
var b = new SortedList(3,1,2);
b.add(4,0); //b inherits the add() method from ArrayList
dwn(b.toArray() ); //b inherited the toArray() method from ArrayList
b.sort(); //b self-implemented sort() method
dwn(b.toArray());
dwn(b );
dwn(b.size()); //b inherits the size() method from Collection

2, example of prototypal inheritance:
Copy code The code is as follows:

//포인트 유형 정의
함수 포인트(차원)
{

this.dimension = 차원
}

//정의 Point2D 유형, "상속" 포인트 유형
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는 Point를 상속합니다

//Point3D 유형을 정의하고 Point 유형도 상속합니다
function Point3D(x, y, z)
{
this.x = x; >this.y = y;
this.z = z;
}
Point3D.prototype = new Point(3); //Point3D도 Point를 상속합니다

//구성 A Point2D 객체
var p1 = new Point2D(0,0);
//Point3D 객체 생성
var p2 = new Point3D(0,1,2)

dwn( p1 .dimension);
dwn(p2.dimension);
dwn(p1instanceofPoint2D); //p1은 Point2D입니다.
dwn(p1instanceofPoint); //p1도 Point입니다. dwn(p2 instanceof Point); //p2는 ​​Point입니다


위의 두 메서드가 가장 일반적으로 사용됩니다.
3, 인스턴스 상속 메서드 예:
이 메서드 예를 이야기하기 전에 , 생성 상속 방법의 한계에 대해 다음과 같이 이야기해 보겠습니다.



코드 복사 코드는 다음과 같습니다. function MyDate ()
{
this.base = Date;
this.base.apply(this, 인수)
}
var date = new MyDate( );
alert(date .toGMTString); //정의되지 않음, date는 Date 유형에서 상속되지 않으므로 toGMTString 메소드가 없습니다.


핵심 객체의 일부 메소드는 상속될 수 없습니다. 핵심 객체가 우리만큼 사용자 정의되지 않았기 때문에 생성자 일반 객체처럼 생성자에서
할당 또는 초기화 작업
을 수행하고 이를 프로토타입 상속으로 바꾸는 것은 어떻습니까? ,



코드 복사 코드는 다음과 같습니다. function MyDate(){ }
MyDate.prototype=new Date();
var date=new MyDate();
alert(date.toGMTString); //'[object]'는 날짜 객체가 아닙니다. Date 유형을 상속하지 않습니다!


이제 인스턴스 상속으로 전환합니다.


코드를 복사합니다. 코드는 다음과 같습니다. function MyDate()
{
var instance = new Date() //인스턴스는 새로 생성된 날짜 객체입니다.
instance.printDate = function(){
document.write("

"instance.toLocaleString() "

")
} //printDate() 메서드를 인스턴스로 확장
//인스턴스를 반환합니다. constructor Value return
}
var myDate = new MyDate();
dwn(myDate.toGMTString()); //이번에는 올바른 시간 문자열이 출력된 것 같습니다. . 인스턴스


, 상속 성공
myDate.printDate(); //반환 인스턴스가 없으면 프라이빗 개체 메서드이므로 첨자로 액세스할 수 없습니다.
4 , 상속 방법 복사 예:



코드 복사 코드는 다음과 같습니다. Function.prototype .extends = function(obj)
{
for(var Each in obj)
{
this.prototype[each] = obj[each]
//의 속성을 복사합니다. 그러나 느리고 문제가 발생하기 쉽습니다
//그래서 이 "상속" 방법은 일반적으로 권장되지 않습니다
}
}
var Point2D = function(){
//...
}
Point2D.extends(new Point())
{
//...
}


이 상속 메서드 거의 사용되지 않는 것 같습니다.
5, 혼합 상속 예:



코드 복사 코드는 다음과 같습니다. function Point2D( x, y)
{
this.x = x;
this.y = y
}
function ColorPoint2D(x, y, c)
{
Point2D .call(this, x, y); //부모 클래스의 생성자를 호출하는 생성 상속입니다.
//이전 예에서는
과 동일합니다.//this.base= Point2D ;//this.base.call(this,x,y);
this.color = c;
}
ColorPoint2D.prototype = new Point2D(); 여기에서 상속하고 ColorPoint2D가 Point2D 객체를 프로토타입으로 사용하도록 합니다



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn