Home > Web Front-end > JS Tutorial > Javascript object-oriented programming_js object-oriented

Javascript object-oriented programming_js object-oriented

WBOY
Release: 2016-05-16 17:55:10
Original
1142 people have browsed it

Importance of Javascript
Usage rate
1. In web applications, JavaScript language is basically used when it comes to front-end interface programming;
2. Web2.0 and Ajax promoted the JavaScript language.
3. With the large number of c/s applications switching to b/s and the continuous promotion of rich client technology, the application scope of javascript language will continue to increase;
Characteristics of javascript
Simple
Dynamic
Object-based (object-oriented)

Javascript object-oriented overview
Javascript is an object-oriented (based on) dynamic scripting language. ) and event-driven (EventDriven) scripting language with security features. It has various features unique to object-oriented languages, such as encapsulation, inheritance and polymorphism. But for most people, we only use JavaScript as a functional language and only use it for some simple front-end data input verification and to achieve some simple page dynamic effects. We have not fully grasped the various aspects of dynamic languages. characteristic.
In many excellent Ajax frameworks, such as ExtJS, JQuery, etc., the object-oriented features of javascript are widely used. To make good use of ext technology, the advanced features of javascript and the object-oriented language features are what we must fully grasp.

Relevant knowledge of Javascript
The development history of Javascript
The three major components of Javascript
ECMAScript
Syntax data type statement keyword reserved word operator object
DOM (Document Object Model)
BOM (Browser Object Model)

Discussion on the flexible features of JavaScript
1. The spiritual test of dynamic language
Javascript as a It is a dynamic language with very flexible features. In the process of using it, you need to flexibly master and apply its dynamic characteristics to be able to use it with ease.
Consider the following output

Copy the code The code is as follows:

function Animal(name) {
this.name=name;
this.age=0;
};
var a1=Animal;//Output:
var a2=Animal();//Output:
var a3=new Animal();//Output:
var a4=new Animal;//Output:


Data types in Javascript
Basic data types
Numbers (Numbers)
Strings (Strings)
Boolean
Special values ​​(null, undefined, NaN).
Object type Object
Objects are complex data types. Objects can contain basic types, objects, functions, etc. Arrays are an object type. For JavaScript, it can be said that everything is an object, including classes! .
var c=new Object();
1. Numeric type
Numeric type is a basic data type that exists in all languages. Numeric types in JavaScript mainly include integers ( There are two types: Int) and floating point (Float), but in fact both types are stored in memory in the form of floating point. Numeric types in JavaScript generally appear in programs in the form of numeric constants. Generally, they are based on decimal data, consisting of 10 numbers from 0 to 9, such as 110, 150, etc., and they can also start with 0x Hexadecimal data (composed of 16 characters from 0-9 and a to f), for example, 0xff converted to decimal is 255 (i.e. 15*16 15 = 255); some JavaScript implementations also support octal data, That is, data starting with 0 (composed of 8 numbers from 0 to 7). For example, if the octal data 0377 is converted into decimal, it is 255, that is (3*64 7*8 7 = 255).
2. Character type
Strings are composed of various characters, numbers and special strings. Single quotes or double quotes can be used directly in the program to generate string constants. There cannot be a carriage return character in the string. To include a carriage return character in the string, you need to use an escape character. . Here are some simple string constants:
"" // The empty string: it has zero characters
'testing'
"3.14"
'name="myform"'
" Wouldn't you prefer O'Reilly's book?"
"This stringnhas two lines"
"π is the ratio of a circle's circumference to its diameter"

3、Boolean
The Boolean type is used to represent true or false. In JavaScript, when used for Boolean operations, data other than 0, null characters, null, undefined, NaN, etc. all represent true.
if(0||""||false||null||undefined||NaN)alert("There is a condition that returns true");
The only Boolean constants are false and true, False and True are not constants .

4. Object type
Javascript is an object-based language, and objects are its core.

Program flow control
Sequential structure
if conditional selection statement
switch selection statement
while loop statement
do while statement
for loop statement
break and continue statement

for...in loop statement
for (variable in collection or object)
{
Execution statement block
}
Copy code The code is as follows:


var as={id:5,name:'test '};
for(var x in as)
{
output = x "=" as[x];
}
alert(output);

Logical operator
&&
Logical AND, when both the left and right operands are true, the return value is true, otherwise it returns false.

Logical OR, when both the left and right operands are false, return the first value that is not false or false.
!
Logical negation, when the operand is true, the return value is false, otherwise it returns true.
Note:
In logical operations, 0, "", false, null, undefined, and NaN all represent false.

Definition and call of function
The format of defining a function is as follows:
function function name (parameter list)
{
Program code
return expression;
}
Copy code The code is as follows:



undefined
alert("sum=" square(2,3));

Several ways to call functions:
Function name (passed to Parameter 1 of the function, parameter 2 passed to the function,….)
Variable = function name (parameter 1 passed to the function, parameter 2 passed to the function,….)
For function calls with return values , you can also use the returned result directly in the program, for example: alert("sum=" square(2,3));
A function that does not specify any function value returns undefined.

Parameter variability (arguments) of the function
Copy code The code is as follows:



Up to 255. The number of parameters that the function hopes to provide can be returned through the length of the function object.
Variability of function parameters
function add(s,b){
if(s)alert(“The first parameter is:” s);
if( !b)alert("No second parameter!");
else alert("The second parameter is:" b);
}
arguments
Arguments is an array-like but not The object of an array is said to be similar to an array because it has the same access properties and methods as an array. The value of the corresponding single parameter can be accessed through arguments[n], and it has the array length attribute length.
How to write a method that can realize the sum of any number?
alert(sum(1,2,3));//Output 6
alert(sum(100,200,500,900));// Output 1700

Use Function class to create functions
Basic syntax format for creating dynamic functions:
var varName = new Function(argument1,...,lastArgument);
Description:
All parameters must be of string type, and the last parameter must be the functional program code of this dynamic function.
Example:
Copy code The code is as follows:




Think more :
What is the role of dynamic functions, and under what circumstances should dynamic functions be used.

Closure (closure)
Javascript closure saves a copy of the variables it obtains from the upper-level function or scope in another scope ( key-value pairs), and these key-value pairs will not be destroyed when the execution of the upper-level function is completed.
In this way, after executing var c=a(), variable c actually points to function b. Variable i is used in b. After executing c(), a window will pop up to display the value of i (first The times are 1). This code actually creates a closure. Why? Because the variable c outside function a refers to the function b inside function a, that is to say:

When the internal function b of function a is referenced by a variable outside function a, a so-called function is created. "closure".
Copy code The code is as follows:

function a() {
var i = 0;
function b() {
alert( i);
}
return b;
}
var c = a();
c();

The function of the closure is to prevent Javascript’s garbage collection mechanism GC from collecting it after a is executed and returned. The resources occupied by a, because the execution of a's internal function b needs to depend on the variables in a.

The scope of the function and this
1. You can use this in a function or method to refer to the current object where the function is located
2. When the current object of the function is not explicitly specified object, the scope is window
3. You can use call and apply to dynamically change the scope of function execution

Copy code The code is as follows:

var b1={v:"this is b1"};
var b2={v:"this is b2"};
function b (d){
alert(this.v);
}
b();//Output:
window.b();//Output:
b.call(b1 );//Output:
b.apply(b2);//Output:


Lexical scope. In layman's terms, the scope of a JavaScript variable is determined when it is defined rather than when it is executed. That is to say, the lexical scope depends on the source code, and the compiler can determine it through static analysis, so the lexical scope is also called the static scope ( static scope). However, it should be noted that the semantics of with and eval cannot be realized only through static technology, so it can only be said that the scope mechanism of JavaScript is very close to lexical scope.
The JavaScript engine will create a new function when executing each function instance. An execution context. The execution environment contains a call object
The call object is a scriptObject structure (scriptObject is a set of static systems related to functions, consistent with the life cycle of function instances), which is used to save the internal variable table varDecls, Embedded function table funDecls, parent reference list upvalue and other syntax analysis structures (note that information such as varDecls and funDecls are obtained during the syntax analysis stage and are saved in the syntax tree. When the function instance is executed, this information will be removed from the syntax tree copied to scriptObject).

apply and call: Their function is to bind the function to another object to run. The only difference between the two is in the way of defining parameters:
apply(thisArg,argArray);
call(thisArg[,arg1,arg2…]]);
That is, the this pointer inside all functions will be assigned to thisArg, which can achieve the purpose of running the function as a method of another object.

Instructions for apply
If argArray is not a valid array or is not an arguments object, a TypeError will be caused. If neither argArray nor thisArg is provided, the Global object will be used as thisArg and no arguments can be passed.

Description of call The
call method changes the object context of a function from the initial context to the new object specified by thisArg. If the thisArg parameter is not provided, the Global object is used as thisArg

The point:
There is another trick in applying call and apply, which is to use call and apply After applying another function (class), the current function (class) has the methods or attributes of the other function (class).
In JavaScript executed by browsing, the scope of the object is window by default.
c.run();
window.c.run();

System functions in JavaScript (Global class)
encodeURI and encodeURIComponent methods
Returns the result of encoding a URI string.
decodeURI and decodeURIComponent() methods
Decode an encoded URI string into the original string and return it.
parseInt method
Convert a string into an integer according to the specified base. The syntax format is: parseInt(numString, [radix]). If the second argument is not specified, strings prefixed with '0x' are treated as hexadecimal, strings prefixed with '0' are treated as octal, and all other strings are treated as decimal.
parseFloat method
Convert a string into the corresponding decimal.
isNaN method
is used to detect whether the return value of parseInt and parseFloat methods is NaN.
escape method
Returns the result string after encoding a string. All spaces, punctuation, accents, and any other non-ASCII characters are replaced with the %xx encoding, where xx is equal to the hexadecimal number representing the Unicode encoding of the character. Characters with a character value greater than 255 are stored in the %uxxxx format.
unescape method
Decodes a result string encoded by the escape method into the original string and returns it. The
eval method
executes the parameter string as a JavaScript expression.

JavaScript internal class
Dynamic object
Use the format of "object instance name.member" to access its properties and methods.
Static object
Directly use the format of "object name.member" to access its properties and methods.

Object class (object)
Number class (object)
String class (object)
Math class (object)
Date class (object)
toString method

Object class
The Object class is the base class of all JavaScript classes, providing a simple way to create custom objects without the need for programmers to define constructors.
Main attributes:
constructor-the constructor of the object
prototype-obtains the prototype object of the class, static property
Main methods:
hasOwnProperty(property)-whether it belongs to the properties defined by this class
isPrototypeOf(object) - whether it is the prototype of the specified class
propertyIsEnumerable(property) - whether it is an enumerable property
toString() - returns the string corresponding to the object
valueOf() - returns the corresponding object Primitive type value



Number class
Number class represents a data class, including some static members and numerical processing methods.
Static attributes:
MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN
Main methods:
toFixed(n) - take the number of decimal places and automatically round
toPrecision(n) - whether it is specified Class prototype
propertyIsEnumerable(property) - Whether the property can be enumerated
toString() - Returns the string corresponding to the object
valueOf() - Returns the original type value corresponding to the object

Copy code The code is as follows:




String Class
length attribute
anchor, big, bold, fontcolor, link and other methods
charAt method
Note: The index position of the first character in a string is 0, and so on. .
charCodeAt method
Note: The returned result is the unicode encoding of the character.
concat method, connection string
indexOf method and lastIndexOf method
match, search method
replace, split method
slice method
Description: str1.slice (0) and str1.slice(0,-1) both return the entire string.
substr, substring method
The content returned by the substring method does not include the character at the end position.
toLowerCase, toUpperCase methods

Math class
Attributes:
E, represents the mathematical constant e, which is approximately equal to 2.718.
LN10, represents the natural logarithm of 10, which is approximately equal to 2.302.
LN2, represents the natural logarithm of 2, which is approximately equal to 0.693.
PI, represents the value of the mathematical constant ∏, which is approximately equal to 3.14159.
SQRT1-2, represents one-quarter of the square root of 2, which is approximately equal to 0.707.
SQRT2, represents the square root of 2, which is approximately equal to 1.414.

Method:
abs method, returns the absolute value of the number.
The sin and cos methods return the sine and cosine values ​​of numbers respectively.
The asin and acos methods return the arcsine and arccosine values ​​of the number respectively.
random method, returns a pseudo-random number between 0 and 1
The Math object is a static class. The new keyword cannot be used to create an object instance. It should be accessed directly using the format of "object name.member" Its properties or methods, for example, var num = Math.random();

Date class
toGMTString method returns the string form of the date represented by the Date object instance, which The string is in Greenwich Mean Time (GMT) format, for example, "05 Jan 1996 00:00:00 GMT".
getYear, getMonth, getDate, getDay methods
getHours, getMinutes, getSeconds, getMilliseconds methods
getTime method, returns the date from 0:00:00 on January 1, 1970 to the Date object instance representative The number of milliseconds until the time.
Copy code The code is as follows:



Construction method: Date(), Date(dateVal), Date(year, month, date[, hours[, minutes[, seconds[,ms]]] ])
parse method, analyzes a string representing date and time, and returns the time value it represents, which is expressed in milliseconds since 0:00:00 on January 1, 1970. The parse method is a static method.

toString method
toString method is a member method of all internal objects in JavaScript. Its main function is to convert the data in the object into a string in a certain format. Representation, the specific conversion method depends on the type of object.

Example:
Copy code The code is as follows:



Array class
Three construction methods:
Array()
Array(4)
Array(3.5,"abc",3)

Array sorting example:
Copy code The code is as follows:



Attributes and methods of the Array class
length-get the length of the array;
concat-concatenate arrays;
join-convert the array into a string;
pop-pop an element;
push - put an element;
reverse - reverse the order of elements in the data;
shift - remove the first element;
slice - intercept the array;
sort - sort the array;
unshift - Append elements in front;

Use objects to implement arrays
Copy code The code is as follows:





User-defined classes and objects
1. Factory method - use new Object to create objects and add related properties;
2. Use constructors to define classes.
3. Use prototype
4. Constructor and prototype mixing method
5. Dynamic prototype method
Instance
Car class (object)
Attribute:
color-color
doors-the number of doors
price-price
drivers-drivers
Method:
showColor-show the color of the car

typeof and instanceof operators
delete Operator is used to delete specified members of an object.
typeof xx-string returns the type of xx object or undefined.
var d=7.5;
alert(typeof d);
alert(typeof d2);
alert(typeof new Object());
alert(typeof Object);

xx instanceof class name, returns boolean type:
Copy code The code is as follows:




delete and void operators
delete operator is used to delete specified members of an object.
var d=new Object();
d.p1="this is p1";
alert(d.p1);
delete d.p1;
alert(d.p1 );
delete can only delete user-defined members.
delete d.toString;
alert(d.toString());
void is used to convert any number to undefined.
var d=new Object();
alert(void(d));
Application scenario:
Click Me

Modification of classes
1. Detailed explanation of prototype
2. Adding new methods to existing classes
3. Redefining methods of classes
4 , super post binding

prototype is an attribute of the Function object. When we access a member of the object, we first look inside the object. If we cannot find it, we look for it in the prototype object of the class where the object is located. .

Encapsulation
Encapsulation: Encapsulation, that is, encapsulating objective things into abstract classes, and the class can only allow its own data and methods to be operated by trusted classes or objects, and provide information to untrusted ones. hide.
In JavaScript, encapsulation can be achieved through closures, see code examples.
Covers simple examples of javascript public member definitions, private member definitions, and privileged method definitions!
Copy code The code is as follows:

<script> <br>//Define a javascript class<br>function JsClass(privateParam/* */,publicParam){//Constructor<br>var priMember = privateParam; //Private variables <br>this.pubMember = publicParam; //Public variables<br>//Define private methods <br>function priMethod(){ <br>return "priMethod()"; <br>} <br>//Define privileges Method<br>//Privileged methods can access all members<br>this.privilegedMethod = function(){ <br>var str = "This is a privileged method, I called it "; <br>str = " Private variable: " priMember "n"; <br>str = " Private method: " priMethod() "n"; <br>str = " Public variable: " this.pubMember "n" ; <br>str = "Public method:" this.pubMethod(); <br><br>return str; <br>} <br>} <br>//Add public method <br>//Cannot call private Variables and methods <br>JsClass.prototype.pubMethod = function(){ <br>return "pubMethod()"; <br>} <br><br>//Use an instance of JsClass <br>JsObject = new JsClass( "priMember","pubMember"); <br><br>//alert(JsObject.pubMember);//Pop up pubMember information<br>//alert(JsObject.priMember);//Pop up undefined information<br>/ /alert(JsObject.pubMethod());//Pop up pubMethod information<br>//alert(JsObject.priMethod());//Pop up the error "The object does not support this property or method"<br>alert(JsObject. privilegedMethod()); <br></script>



Covers simple examples of javascript public member definitions, private member definitions, and privileged method definitions! 🎜>
<script> <div class="codebody" id="code19821">//Define a javascript class<br> function JsClass(privateParam/* */,publicParam){//Constructor<br>var priMember = privateParam; //Private variable<br>this.pubMember = publicParam; //Public variable<br>//Define private method<br>function priMethod(){ <br>return "priMethod()"; <br>} <br>//Define privileged methods<br>//Privileged methods can access all members<br>this.privilegedMethod = function() { <br>var str = "This is a privileged method, I called "; <br>str = " Private variable: " priMember "n"; <br>str = " Private method: " priMethod() "n"; <br>str = " Public variable: " this.pubMember "n" ; <br>str = "Public method:" this.pubMethod(); <br><br>return str; <br>} <br>} <br>//Add public method <br>//Cannot call private Variables and methods <br>JsClass.prototype.pubMethod = function(){ <br>return "pubMethod()"; <br>} <br><br>//Use an instance of JsClass <br>JsObject = new JsClass( "priMember","pubMember"); <br><br>//alert(JsObject.pubMember);//Pop up pubMember information<br>//alert(JsObject.priMember);//Pop up undefined information<br>/ /alert(JsObject.pubMethod());//Pop up pubMethod information<br>//alert(JsObject.priMethod());//Pop up the error "The object does not support this property or method"<br>alert(JsObject. privilegedMethod()); <br></script>


Inheritance
A main function of object-oriented programming (OOP) language is "inheritance". Ability: It can use all the functions of existing classes and extend these functions without rewriting the original class
1. Object impersonation
2. call and apply
3. Prototype chain
4. Mixed method

Inheritance-Object impersonation


function classA(name) {
this.name=name;
this.showName=function(){alert(this.name);}
}
function classB (name) {
this.newMethod = classA;
this.newMethod(name);
}
obj = new classA("hero");
objB = new classB("dby ");
obj.showName(); // print hero
objB.showName(); // print dby indicates that classB inherits the method of classA.
Object impersonation can achieve multiple inheritance, such as
function classz(){
this.newMethod = classX;
this.newMethod();
delete this.newMethod;
}


But if classX and classY have For the same attributes or methods, classY has high priority.

Inherited-call method
The call method is a method similar to the classic object impersonation method, and its first parameter is used as the object of this , other parameters are passed directly to the function itself.


function sayName (perfix) {
alert(perfix this.name);
}
obj= new Object();
obj.name="hero";
sayName.call(obj," hello," );
function classA(name) {
this.name=name;
this.showName=function(){alert(this.name);};
}
function classB(name) {
classA.call(this,name);
}
objB = new classB("bing");
objB.showName();////Description classB Inherit the showName method of classA


Inherited-apply method
The apply() method has 2 parameters, one is used as this object, and the other is the parameter array passed to the function.
Copy Code The code is as follows:

function sayName(perfix) {
alert(perfix this.name);
}
obj= new Object ();
obj.name="hero";
sayName.aplly(obj,new Array("hello,") );

Inheritance-Prototype Chain
prototype Any properties and methods of the object will be passed to all instances of the corresponding class. This is how the prototype chain shows inheritance.
function classA (){}
classA.prototype.name="hero";
classA.prototype.showName=function(){alert(this.name)}
function classB(){}
classB.prototype=new classA();
objb = new classB()
objb.showName();//print hero indicates that b inherits the method of a
It should be noted here that when calling the constructor of classA, no parameters are passed to it. This is the standard practice of the prototype chain to ensure that the function is constructed The function does not have any parameters.
And all attributes and methods of the subclass must appear after the prototype attribute is assigned, because the value assigned before it will be deleted. Because the prototype attribute of the object is replaced with a new object, The original object with the new method added will be destroyed.

Inheritance-mixed method
is to use the impersonation method to define the constructor properties and the prototype method to define the object methods.
Copy code The code is as follows:

function classA(name) {
this.name=name;
}
classA.prototype.showName=function(){alert(this.name)}
function classB(name) {
classA.call(this,name);
}
classB.prototype = new classA();
classB.prototype.showName1=function(){alert(this.name "*****");};
obj = new classB("hero");
obj .showName();
obj.showName1();

In the constructor of classB, inherit the name attribute in classA by calling the call method, and use the prototype chain to inherit the showName method of classA.

Discussion on method overloading in JavaScript
Method overloading and overriding
The method itself in Javascript has variable parameters and does not support overloading operations. But we can freely detect the parameters of the method in the method body to achieve the effect of overloading. (Example of using variadic parameters or arguments to simulate overloading).
Overwriting, also called overwriting, means that the method defined in the subclass replaces the method of the parent class

Discussion on polymorphism (polymorphisn) in JavaScript
Polymorphism (polymorphisn): Yes A technique that allows you to set a parent object to be equal to one or more of its child objects. After assignment, the parent object can behave in different ways based on the properties of the child objects currently assigned to it. To put it simply, it is one sentence: It is allowed to assign a pointer of a subclass type to a pointer of a parent class type. Polymorphism is to achieve another purpose - interface reuse! The role of polymorphism is to ensure the correct call when using a certain attribute of an instance of any class in the "family tree" when the class inherits and derives.
var a=[a1,a2,a3];
Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template