SoFunction
Updated on 2025-04-13

Javascript object-oriented programming

The 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 promote the javascript language.
3. With a large number of c/s applications turning to b/s and rich client technology continue to promote, the application scope of javascript language will continue to increase;
Features of javascript
Simple
dynamic
Object-based (object-oriented)

Javascript object-oriented overview
Javascript is a dynamic scripting language for ()object-based, and is a scripting language based on object (Object) and event-driven (EventDriven) and has security performance. It has various characteristics 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 implement some simple page dynamic effects, etc. We have not fully grasped the various characteristics of dynamic languages.
In many excellent Ajax frameworks, such as ExtJS, JQuery, etc., we must fully grasp the object-oriented characteristics of javascript. We must use the ext technology, the advanced features of javascript, and the object-oriented language characteristics.

Javascript related knowledge
The development history of Javascript
Three components of Javascript
ECMAScript
Syntax\Data Type\State\Keywords\Reserved Words\Operators\Objects
DOM(Document Object Model)
BOM(Browser Object Model)

Discussion on the flexible features of JavaScript
1. Spirituality test of dynamic language
As a dynamic language, Javascript has very flexible I-spreading. During the use process, it needs to flexibly master and apply its dynamic features to be able to be easy.
Think about the output below

Copy the codeThe code is as follows:

function Animal(name){
=name;
=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
Strings
Boolean
Special values ​​(null, undefined, NaN).
Object type Object
Objects are complex data types, and the object 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. Number type
Number types are basic data types that exist in all languages. The number types in javascript mainly include two types: integer (Int) and floating point (Float), but the essence of both types are stored in memory in the form of floating point. Number types generally appear in programs in JavaScript in the form of numeric constants. Generally, they are based on decimal data, composed of 10 numbers 0-9, such as 110, 150, etc., and can also be hexadecimal data starting with 0x (composed of 0-9 and 16 characters such as a to f). For example, 0xff is converted to decimal, which is 255 (that is, 15*16 + 15 = 255); some JavaScript implementations also support octal data, that is, data starting with 0 (composed of 8 numbers 0-7), such as 0377, which is converted to decimal, which is 255, that is (3*64 + 7*8 + 7 = 255).
2. Character type
A string consists of various characters, numbers and special strings. Single 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 carriage return in the string, you need to use escape characters\n. 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 string\nhas two lines"
"π is the ratio of a circle's circumference to its diameter"

3. Boolean
Boolean type is used to represent true or false. In javascript, when used for Boolean operations, data except 0, null, undefined, NaN, etc. are all represented by true.
if(0||""||false||null||undefined||NaN)alert("A condition returns true");
Boolean constants only have false and true, False and True are not constants.

4. Object type
JavaScript is an object-based language, and objects are at their 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 statements

for...in loop statement
for(variable in set or object)
{
Execute statement block
}
Copy the codeThe code is as follows:

<script language="javascript">
var as= [1,4,5,6],output="";
for(var x in as)
{
output += " x= " + as[x];
}
alert(output);
</script>
var as={id:5,name:'test'};
for(var x in as)
{
output += x+"="+as[x];
}
alert(output);

Logical operators
&&
Logical and, when both operands on the left and right sides are true, the return value is true, otherwise false is returned.

Logical or, when both the operands on the left and right sides are false, return the first value or false that is not false.
!
Logical non, when the operand is true, the return value is false, otherwise true.
Notice:
In logical operations, 0, "", false, null, undefined, and NaN all represent false.

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

<script language="javascript">
var msg = "global variable";
function square(x,y)
{
var sum;
sum = x*x + y*y;
return sum;
}
function show()
{
var msg = "local variable";
alert(msg);
}
//var sum;
alert("sum=" + sum);
sum=square(2,3);
alert("sum=" + sum);
show();
</script>

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

Several ways to call functions:
Function name (parameter 1 passed to function, parameter 2 passed to function,….)
Variable = function name (parameter 1 passed to function, parameter 2 passed to 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 of functions (arguments)
Copy the codeThe code is as follows:

<script language="javascript">
function sum()
{
var s= 0;
for(var i=0; i<; i++)
s+= arguments[i];
return s;
}
sum(1,2);
sum(3,4,5);
</script>

Up to 255. Through the length of the function object, you can return the number of parameters that the function wants to provide.
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 object, but not an array. It is said that it is similar to an array because it has the same access properties and methods as arrays. It can access the value of the corresponding single parameter by arguments[n] and have the array length attribute length attribute.
How to write a method that can achieve summing of any number?
alert(sum(1,2,3));//Output 6
alert(sum(100,200,500,900));//Output 1700

Create functions using Function class
Basic syntax format for creating dynamic functions:
var varName = new Function(argument1,...,lastArgument);
illustrate:
All parameters must be string type, and the final parameter must be the functional program code of this dynamic function.
example:
Copy the codeThe code is as follows:

<script language="javascript">
var square = new Function ("x","y",
"var sum;sum= x*x + y*y;return sum;");
alert(square(3,2));
var alsoDoSquare = doAdd;
alert(alsoDoSquare (3,2));
</script>


Think more:
What are the functions of dynamic functions and under what circumstances do dynamic functions use?

closure
A Javascript closure is to save a copy of variables (key-value pairs) it obtains from the previous level function or scope in another scope, and these key-value pairs will not be destroyed as the execution of the previous level function is completed.
In this way, after executing var c=a(), the variable c actually points to function b, and the variable i is used in b. After executing c(), a window will pop up to display the value of i (the first time is 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,:

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

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

The purpose of the closure is that after a is executed and returned, the closure makes the Javascript garbage collection mechanism GC not recover the resources occupied by a, because the execution of a internal function b of a needs to rely on the variables in a.

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

Copy the codeThe code is as follows:

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


Lexcical scope. In layman's terms, the scope of javascript variables is determined at definition rather than at execution time. That is to say, the lexical scope depends on the source code, and the compiler can determine it through static analysis. Therefore, the lexical scope is also called static scope. However, it should be noted that the semantics of with and eval cannot be implemented only through static technology, so it can only be said that the scope mechanism of javascript is very close to the lexical scope.
When executing each function instance, the javascript engine creates an execution context. The execution environment contains a call object (call object)
The call object is a scriptObject structure (scriptObject is a static system 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 in the syntax analysis stage and are saved in the syntax tree. When the function instance is executed, this information will be copied from the syntax tree to the scriptObject).

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

Apply instructions
If argArray is not a valid array or is not an arguments object, a TypeError will be generated. If no arguments are provided, the Global object will be used as thisArg and no arguments can be passed.

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

The point:
There is another trick in applying call and apply, that is, after using call and apply to apply another function (class), the current function (class) has methods or attributes of another function (class).
In the JavaScript that browses and executes, the scope of the object is window by default.
();
();

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

JavaScript internal classes
Dynamic Objects
Use the "Object Instance Name. Member" format to access its properties and methods.
Static Objects
Use the "Object Name. Member" format directly 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 an easy way to create custom objects without requiring programmers to define constructors.
Main attributes:
constructor-Object constructor
prototype-Get the prototype object of the class, static properties
Main methods:
hasOwnProperty(property) - Whether it belongs to the attribute defined in this class
isPrototypeOf(object) - Is it a prototype of the specified class
propertyIsEnumerable(property) - An example property
toString() - Returns the string corresponding to the object
valueOf() - Returns the original type value corresponding to the object

<script language="javascript">
function getAttributeValue(attr)
{
alert(person[attr]);
}
var person = new Object();
= "zs";
= 18;
getAttributeValue("name");
getAttributeValue("age");
</script>

Number class
The Number class represents a data class, including some static members and numerical processing methods.
Static properties:
MAX_VALUE、MIN_VALUE、NEGATIVE_INFINITY、POSITIVE_INFINITY、NaN
Main methods:
toFixed(n) - Take the number of decimal places and automatically round up
toPrecision(n) - Is it a prototype of the specified class?
propertyIsEnumerable(property) - An example property
toString() - Returns the string corresponding to the object
valueOf() - Returns the original type value corresponding to the object

Copy the codeThe code is as follows:

<script language="javascript">
var oNumberObject = new Number(99);
alert((2)); //outputs “99.00”
</script>


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 characters.
concat method, concatenate string
indexOf method and lastIndexOf method
match, search methods
replace, split methods
slice method
Description: (0) and (0,-1) both return the entire string.
substr, substring methods
The content returned by the substring method does not contain characters at the end position.
toLowerCase, toUpperCase methods

Math class
property:
E, represents the mathematical constant e, which is approximately equal to 2.718.
LN10, representing the natural logarithm of 10, is approximately equal to 2.302.
LN2, representing the natural logarithm of 2, is approximately equal to 0.693.
PI, representing the value of the mathematical constant ∏, is approximately equal to 3.14159.
SQRT1-2, representing one-part of the square root of 2, is approximately equal to 0.707.
SQRT2, representing the square root of 2, 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 the numbers respectively.
Asin and acos methods return the inverse sine and inverse cosine values ​​of the numbers respectively.
random method, returns a pseudo-random number between 0 and 1
A Math object is a static class and cannot use the new keyword to create object instances. It should directly use the format of "object name. member" to access its properties or methods, for example, var num = ();

Date class
toGMTString method returns the string form of a date represented by the Date object instance, which uses Greenwich Standard 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 number of milliseconds from 0:00:00 on January 1, 1970 to the time represented by the Date object instance.
Copy the codeThe code is as follows:

<script language="javascript">
var current_time = new Date();
var strDate = current_time.getYear() + "year";
strDate += current_time.getMonth() + "month";
strDate += current_time.getDate() + "Day";
strDate += current_time.getHours() + ":";
strDate += current_time.getMinutes() + ":";
strDate += current_time.getSeconds();
alert(strDate);
</script>

Constructor: Date(), Date(dateVal), Date(year, month, date[, hours[, minutes[, seconds[, ms]]]])
The parse method analyzes a string representing date and time, and returns the time value it represents, which is expressed as a millisecond value calculated from 0:00:00 on January 1, 1970. The parse method belongs to a static method.

toString method
The 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 of a certain format to represent it. The specific conversion method depends on the type of the object.

For example:
Copy the codeThe code is as follows:

<script language="javascript">
var x = 328;
alert("hex=“ + (16) + " bin=“ + (2));
</script>

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

Example of array sorting:
Copy the codeThe code is as follows:

<script language="javascript">
var arr = new Array();
arr[0] = 3.5;
arr[1] = "abc"
arr[2] = 3;
();
var x,str = "";
for(x in arr)
{
str += x + ":“ + arr[x] + "\n";
}
alert(str);
</script>

Array class properties and methods
length - get the length of the array;
concat - concatenate array;
join - convert array into strings;
pop-pop-pop an element;
push-Put an element;
reverse-Reverse-Reverse the order of elements in the data;
shift-moves the first element;
slice-intercepts array;
sort-sorted array;
unshift - add elements in front;

Implement arrays using objects
Copy the codeThe code is as follows:

<script language="javascript">
function MyArray()
{
= ;
for (var i=0; i<;i++)
{
this[i] = arguments[i];
}
}
var str = "";
var arr = new MyArray(4,3.5,"abc");
for(var i=0; i<; i++)
{
str += arr[i] + "\n";
}
alert(str);
</script>
<script language="javascript">
function MyArray(size)
{
= size;
for (var i=0; i<size; i++)
{
this[i] = "";
}
}
var arr = new MyArray(2);
arr[0] = 3;
arr[1] = "abc";
arr[2] = 4;
var x, str = "";
for(x in arr)
{
str += x + ":" + arr[x] + "\n";
}
alert(str);
</script>


User-defined classes and objects
1. Factory method - Use new Object to create an object and add relevant attributes;
2. Use constructors to define classes.
3. Use prototype
4. Constructor and prototype mixing method
5. Dynamic prototype method
Example
Car class (object)
property:
color-color
doors-number of doors
price-price
drivers-drivers
method:
showColor-Show the color of the car

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

xx instanceof class name, return boolean type:
Copy the codeThe code is as follows:

<script language="javascript">
var o = new String("ab");
alert(o instanceof String);
alert(o instanceof Number);
alert(o instanceof Object);
</script>


delete and void operators
The delete operator is used to delete the specified member 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 the user's self-proclaimed members.
delete ;
alert(());
void is used to convert any number into undefined.
var d=new Object();
alert(void(d));
Application scenario:
<a href=”javascript:(‘about:blank')”>Click Me</a>

Class modification
1. Detailed explanation of prototype
2. Add new methods to existing classes
3. Redefine the method of class
4. Super rear binding

prototype is a property of the Function object. When we access a member of the object, we first look inside the object. If it cannot be found, we look in the prototype object of the class where the object is located.

Package
Encapsulation: Encapsulation means encapsulating objective things into abstract classes, and the class can only allow trusted classes or objects to operate on information that is untrusted.
In JavaScript, encapsulation can be achieved through closures, see code examples.
A simple example covering javascript public member definition, private member definition, privileged method definition!
Copy the codeThe code is as follows:

<script>
//Define a javascript class
function JsClass(privateParam/* */,publicParam){//Constructor
var primary = privateParam; //Private variable
= publicParam; //Public variable
//Define private methods
function priMethod(){
return "priMethod()";
}
//Define privileged method
//Private method can access all members
= function(){
var str = "This is a privileged method, I called \n";
str += " Private variable: " + priMember +"\n";
str += " Private method: " + priMethod() +"\n";
str += " Public variable: " + +"\n";
str += " Public method: " + ();

return str;
}
}
//Add a public method
//Private variables and methods cannot be called
= function(){
return "pubMethod()";
}

//Example using JsClass
JsObject = new JsClass("priMember","pubMember");

//alert();//Popt out pubMember information
//alert();//Undefined information pops up
//alert(());//Popt out pubMethod information
//alert(());//The error pops up "The object does not support this property or method"
alert(());
</script>



A simple example covering javascript public member definition, private member definition, privileged method definition!
Copy the codeThe code is as follows:

<script>
//Define a javascript class
function JsClass(privateParam/* */,publicParam){//Constructor
var primary = privateParam; //Private variable
= publicParam; //Public variable
//Define private methods
function priMethod(){
return "priMethod()";
}
//Define privileged method
//Private method can access all members
= function(){
var str = "This is a privileged method, I called \n";
str += " Private variable: " + priMember +"\n";
str += " Private method: " + priMethod() +"\n";
str += " Public variable: " + +"\n";
str += " Public method: " + ();

return str;
}
}
//Add a public method
//Private variables and methods cannot be called
= function(){
return "pubMethod()";
}

//Example using JsClass
JsObject = new JsClass("priMember","pubMember");

//alert();//Popt out pubMember information
//alert();//Undefined information pops up
//alert(());//Popt out pubMethod information
//alert(());//The error pops up "The object does not support this property or method"
alert(());
</script>


inherit
One of the main functions of the Object-Oriented Programming (OOP) language is "inheritance". Inheritance refers to the ability to use all the functions of an existing class 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
Copy the codeThe code is as follows:

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

However, if classX and classY have the same attributes or methods, classY has a high priority.

Inheritance-call method
The call method makes the method similar to the classic object impersonation method. Its first parameter is used as this object, and other parameters are directly passed to the function itself.
Copy the codeThe code is as follows:

function sayName(perfix) {
alert(perfix+);
}
obj= new Object();
="hero";
(obj,"hello," );
function classA(name) {
=name;
=function(){alert();};
}
function classB(name) {
(this,name);
}
objB = new classB("bing");
();//// Explain that classB inherits classA's showName method

Inheritance-apply method
The apply() method has 2 parameters, one used as this object and one is an array of parameters passed to the function.
Copy the codeThe code is as follows:

function sayName(perfix) {
alert(perfix+);
}
obj= new Object();
="hero";
(obj,new Array("hello,") );

Inheritance-Prototype Chain
Any properties and methods of the prototype object will be passed to all instances of the corresponding class. The prototype chain uses this method to display inheritance.
function classA (){}
="hero";
=function(){alert()}
function classB(){}
=new classA();
objb = new classB()
();//print hero Explain that b inherits a method
It is necessary to note here that when calling classA's constructor, no parameters are passed to it. This is the standard practice of the prototype chain to ensure that the constructor of the function has no parameters.
And all attributes and methods of subclasses must appear after the prototype attribute is assigned, and the value assigned before it will be deleted. Because the object's prototype attribute is replaced with a new object, the original object with the new method added will be destroyed.

Inheritance-mixed method
It is to define constructor attributes using impersonation and define object methods using prototype methods.
Copy the codeThe code is as follows:

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

In the constructor of classB, the name attribute in classA is inherited by calling the call method, and the showName method of classA is inherited by using the prototype chain.

Discussion on method overloading in javascript
Method overloading and overriding
Methods in Javascript are themselves a mutable parameter and do not support overloading operations. But we can freely detect the parameter situation of the method in the body to achieve the effect of overloading. (Example of simulated overloading using variable parameters or arguments).
Overwrite, also known as overwriting, refers to the method defined in the subclass to replace the method of the parent class.

Discussion on polymorphisn in javascript
Polymorphisn: is a technique that allows you to set the parent object to be equal to one or more of its child objects. After assignment, the parent object can operate in different ways according to the characteristics of the child object currently assigned to it. Simply put, it is just a sentence: allowing the subclass type pointer to the parent class type pointer. Polymorphism is to achieve another purpose - interface reuse! The function of polymorphism is to ensure the correct call of a certain attribute of an instance of any class in the "family tree" when inheriting and deriveing.
var a=[a1,a2,a3];