Home >Web Front-end >JS Tutorial >[Recommended] JavaScript object-oriented technology basic tutorial_js object-oriented

[Recommended] JavaScript object-oriented technology basic tutorial_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:55:24860browse

As for the result, after reading it for a long time, I got a general understanding. After careful review, I seem to understand nothing...
This article is a reference to<>Chapter 7, 8, and 9, I will also
try my best to explain the object-oriented technology of JavaScript according to the structure of the original book (object/array->function-->class/constructor /Prototype). For some parts that I am not sure about, I will attach the English sentences of the original text for your reference.
If no explanation is given, all English sentences (except the program body) appearing in the article are Quoted from<>.
-------------------------------- --------------------
Objects and Arrays
What is an object? Put some "name-property" combinations in one Inside the unit, an object is formed. We can understand that the object of
in JavaScript is a collection of "key-value" pairs (An object is a collection of named values. These named values ​​are usually referred to
to as properties of the object.--Section3.5).
"Name" can only be of string type, not other types, and the type of the property is
any (number/string/other object. .). You can use new Object() to create an empty object, or you can simply use "{}" to create an
empty object. The two functions are equivalent.

Copy code The code is as follows:

var emptyObject1 = {}; //Create an empty object
var emptyObject2 = new Object( ); //Create an empty object
var person = {"name":"sdcyst",
"age":18,
"sex":"male"}; //Create an object containing the initial value The object person
alert(person.name); //sdcyst
alert(person["age"]); //18

We can also see from the above example , to access the properties of an object, you can simply use the object name plus "." followed by the name of the property, or you can use the "[]" operator to obtain it. At this time, the property name in [] must be quoted. This is Because the indexes in the object are all of string type. The number of attributes in the javascript object is variable. After creating an object, you can assign any attribute to it at any time.
Copy code The code is as follows:

var person = {};
person.name = "sdcyst";
person[" age"] = 18;
alert(person.name "__" person.age); //sdcyst__18
var _person = {name:"balala","age":23}; //Constructing a When an object is used, the name of the attribute can be marked without quotation marks (name),
//but it is still a string type. When accessing, quotation marks are still required within []
alert(_person["name"] " __" person.age); //balala__23
alert(_person[name]); //undefined
var person = {};
person.name = "sdcyst";
person[" age"] = 18;
alert(person.name "__" person.age); //sdcyst__18
var _person = {name:"balala","age":23}; //Constructing a When an object is used, the name of the attribute can be marked without quotation marks (name),
//but it is still a string type. When accessing, quotation marks are still required within []
alert(_person["name"] " __" person.age); //balala__23
alert(_person[name]); //undefined

To obtain the attributes of an object through the "." operator, you must know the name of the attribute .Generally speaking, the "[]" operator is more powerful in obtaining object attributes.

You can put some expressions in [] to get the value of the attribute.
For example, it can be used in loop control statement, and the "." operator does not have this flexibility.
Copy code The code is as follows:

var name = {"name1":"NAME1", "name2":"NAME2","name3":"NAME3","name4":"NAME4"};
var namestring = "";
for(var props in name) { //Loop name object The attribute name in
namestring = name[props];
}
alert(namestring); //NAME1NAME2NAME3NAME4

namestring = "";
for(var i=0; i<4; i ) {
namestring = name["name" (i 1)];
}
alert(namestring); //NAME1NAME2NAME3NAME4

delete operator You can delete an attribute in an object and use the "in" operator to determine whether an attribute exists.
Copy code Code As follows:

var name = {"name1":"NAME1","name2":"NAME2","name3":"NAME3","name4":"NAME4"};
var namestring = " ";
for(var props in name) { //Loop the property names in the name object
namestring = name[props];
}
alert(namestring); //NAME1NAME2NAME3NAME4

delete name.name1; //Delete name1 attribute
delete name["name3"]; //Delete name3 attribute
namestring = "";
for(var props in name) { // Loop through the property names in the name object
namestring = name[props];
}
alert(namestring); //NAME2NAME4

alert("name1" in name); //false
alert("name4" in name); //true

It should be noted that the attributes in the object are not in order.

The constructor attribute of the object
each A JavaScript object has a constructor attribute. This attribute corresponds to the constructor when the object is initialized (a function is also an object).
Copy code The code is as follows:

var date = new Date();
alert(date.constructor); //Date
alert(date.constructor == "Date"); / /false
alert(date.constructor == Date); //true

Array
We have already mentioned that objects are collections of unordered data, while arrays have A collection of sequential data. The data (elements) in the array are accessed by index (starting from 0).
The data in the array can be of any data type. The array itself is still an object, but due to many characteristics of the array, usually
This is a useful and reasonable simplification; you can treat objects and arrays as separate types
for most of your JavaScript programming.To fully understand the behavior of objects and arrays,
however, you have to know the truth: an array is nothing more than an object with a thin layer of extra
functionality. You can see this with the typeof operator: applied to an array value, it returns
the string "object". --section7.5).
You can use the "[]" operator to create an array, or use Array() constructor to create a new one.

Js code

Copy code The code is as follows:
var array1 = []; //Create an empty array
var array2 = new Array(); //Create an empty array
array1 = [1,"s",[3,4], {"name1":"NAME1"}]; //
alert(array1[2][1]); //4 Access array elements in the array
alert(array1[3].name1); / /NAME1 accesses the object in the array
alert(array1[8]); //undefined
array2 = [,,]; //If there is no value and only commas are filled in, the element at the corresponding index is undefined
alert(array2.length); //3
alert(array2[1]); //undefined
var array1 = []; //Create an empty array
var array2 = new Array(); //Create an empty array
array1 = [1,"s",[3,4],{"name1":"NAME1"}]; //
alert(array1[2][1]); //4 Access the array element in the array
alert(array1[3].name1); //NAME1 Access the object in the array
alert(array1[8]); //undefined
array2 = [ ,,]; //If there is no numerical value but only commas, the element at the corresponding index is undefined
alert(array2.length); //3
alert(array2[1]); //undefined

When using new Array() to create an array, you can specify a default size, the values ​​​​in which are undefined at this time, and you can assign values ​​to them later. However, due to

in javascript The length of the array can be changed arbitrarily, and the contents of the array can also be changed arbitrarily, so the initialized length actually does not have any binding force on the array. For an array, if the index exceeds its maximum length Assignment will change the length of the array, and will assign undefined to the index where there is no assignment
, see the example below.

Js code


var array = new Array(10);
alert(array.length); //10
alert (array[4]); //undefined
array[100] = "100th"; //This operation will change the length of the array and set the values ​​corresponding to indexes 10-99 to undefined
alert(array .length); //101
alert(array[87]); //undefined
var array = new Array(10);
alert(array.length); //10
alert (array[4]); //undefined
array[100] = "100th"; //This operation will change the length of the array and set the values ​​corresponding to indexes 10-99 to undefined
alert(array .length); //101
alert(array[87]); //undefined


You can use the delete operator to delete elements of the array. Note that this deletion only sets the element of the array at that position to undefined, and the length of the array does not change.

We have already used the length of the array. Attribute, the length attribute is a read/write attribute, which means that we can
change the length of the array arbitrarily by changing the length attribute of the array. If length is set to a value less than the length of the array, then the length in the original array Values ​​with indexes greater than length-1 will be deleted. If the value of length
is greater than the length of the original array, the values ​​between them are set to undefined.

Js code
Copy code The code is as follows:

var array = new Array("n1","n2","n3"," n4","n5"); //Array of five elements
var astring = "";
for(var i=0; iastring = array[i];
}
alert(astring); //n1n2n3n4n5
delete array[3]; //Delete the value of the array element
alert(array.length "_" array[3]) //5_undefined

array.length = 3; //Reduce the length of the array
alert(array[3]); //undefined
array.length = 8; / /Expand the length of the array
alert(array[4]); //undefined
var array = new Array("n1","n2","n3","n4","n5"); / /Array of five elements
var astring = "";
for(var i=0; iastring = array[i];
}
alert(astring); //n1n2n3n4n5
delete array[3]; //Delete the value of the array element
alert(array.length "_" array[3]) //5_undefined

array.length = 3; //Reduce the length of the array
alert(array[3]); //undefined
array.length = 8; //Expand the length of the array
alert (array[4]); //undefined

For other methods of arrays such as join/reverse, etc., I will not give examples one by one here.

Through the above explanation , We already know that the attribute value of the object is obtained through the name of the attribute (string type), and the element of the array is obtained through the index
(integer type 0~~2**32-1). The array itself is also an object, so the operation of object properties is completely suitable for arrays.

Js code
Copy code The code is as follows:

var array = new Array("no1","no2");
array["po"] = "props1";
alert(array.length ); //2
//For arrays, array[0] has the same effect as array["0"] (? Not sure, this is true during testing)
alert(array[0] "_ " array["1"] "_" array.po);//no1_no2_props1


Function
I believe everyone has written a lot of javascript functions, so we are just simple here Let me introduce.
Create function:
Copy the code The code is as follows:

function f( x) {.....}
var f = function(x) {......}

Both of the above two forms can create a file named f () function, but the latter form can create anonymous functions
Parameters can be set when defining the function. If the number of parameters passed to the function is not enough, they will correspond in order from the leftmost, and the rest will be assigned undefined. If passed If there are more parameters for function
than the number of parameters defined by the function, the extra parameters will be ignored.



Js code
Copy code The code is as follows:

function myprint(s1,s2,s3) {
alert(s1 "_" s2 "_" s3 );
}
myprint(); //undefined_undefined_undefined
myprint("string1","string2"); //string1_string2_undefined
myprint("string1","string2","string3", "string4"); //string1_string2_string3
function myprint(s1,s2,s3) {
alert(s1 "_" s2 "_" s3);
}
myprint(); // undefined_undefined_undefined
myprint("string1","string2"); //string1_string2_undefined
myprint("string1","string2","string3","string4"); //string1_string2_string3

Therefore, for a defined function, we cannot expect the caller to pass in all the parameters. Those parameters that must be used should be checked in the function body
(using the ! operator), or set to default The value is then or (||) operated with the parameter to obtain the parameter.



Js code
Copy code The code is as follows:

function myprint(s1,person) {
var defaultperson = { //Default person object
"name":"name1",
"age":18,
" sex":"female"
};
if(!s1) { //s1 is not allowed to be empty
alert("s1 must be input!");
return false;
}
person = person || defaultperson; //Accept person object parameter
alert(s1 "_" person.name ":" person.age ":" person.sex);
};

myprint(); //s1 must be input!
myprint("s1"); //s1_name1:18:female
myprint("s1",{"name":"sdcyst", "age":23,"sex":"male"}); //s1_sdcyst:23:male
function myprint(s1,person) {
var defaultperson = { //Default person object
" name":"name1",
"age":18,
"sex":"female"
};
if(!s1) { //s1 is not allowed to be empty
alert("s1 must be input!");
return false;
}
person = person || defaultperson; //Accept person object parameter
alert(s1 "_" person.name " :" person.age ":" person.sex);
};

myprint(); //s1 must be input!
myprint("s1"); //s1_name1:18 :female
myprint("s1",{"name":"sdcyst","age":23,"sex":"male"}); //s1_sdcyst:23:male

The arguments attribute of the function
Inside each function body, there is an arguments identifier, which represents an Arguments object. The Arguments object is very similar
to the Array (array) object, for example The length attribute, to access its value, use the "[]" operator to use the index to access the parameter value. However, the two are completely different
things, and they only have similarities on the surface (for example, modifying the length of the Arguments object attribute does not change its length).

Js code
Copy code The code is as follows:

function myargs() {
alert(arguments.length);
alert(arguments[0]);
}
myargs(); //0 --- undefined
myargs("1",[1,2]); //2 --- 1
function myargs() {
alert(arguments.length);
alert(arguments[0] );
}
myargs(); //0 --- undefined
myargs("1",[1,2]); //2 --- 1 The Arguments object has a callee attribute, Marks the method where the current Arguments object is located. You can use it to implement internal recursive calls of anonymous functions.

Js code
Copy code The code is as follows:

function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x -1);
} (section8.2)
function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x-1);
} (section8.2)

Method--Method
A method is a function. We know that every object contains 0 or more attributes, and the attributes can be of any type. Of course, objects are also included. The function itself is a
object, so we can put a function into an object. At this time, the function becomes a method of the object. If you want to use this method in the future,
can be achieved by using the "." operator through the object name.

Js code
Copy code Code As follows:

var obj = {f0:function(){alert("f0");}}; //The object contains a method
function f1() {alert("f1" );}
obj.f1 = f1; //Add a method to the object

obj.f0(); //f0 f0 is the method of obj
obj.f1(); //f1 f1 is a method of obj
f1(); //f1 f1 is also a function and can be called directly
f0(); //f0 is only a method of obj and can only be called through an object
var obj = {f0:function(){alert("f0");}}; //The object contains a method
function f1() {alert("f1");}
obj.f1 = f1 ; //Add a method to the object

obj.f0(); //f0 f0 is the method of obj
obj.f1(); //f1 f1 is the method of obj
f1() ; //f1 f1 is also a function and can directly call
f0(); //f0 is only a method of obj and can only be called through an object.
The calling of
method requires an object Support, so how to get the properties of the object in the method? We are already familiar with this!this keyword. In the JavaScript method
, we can use this to get the reference to the method caller (object) , thereby obtaining various attributes of the method caller.



Js code
Copy codeThe code is as follows:

var obj = {"name":"NAME","sex":"female"};
obj.print = function() { //Add a method to the object
alert(this .name "_" this["sex"]);
};
obj.print(); //NAME_female
obj.sex = "male";
obj.print(); //NAME_male
var obj = {"name":"NAME","sex":"female"};
obj.print = function() { //Add method to object
alert(this .name "_" this["sex"]);
};
obj.print(); //NAME_female
obj.sex = "male";
obj.print(); //NAME_male

Let’s take a more object-oriented example.

Js code
Copy code The code is as follows:

var person = {name:"defaultname",
setName:function(s){
this.name = s;
},
"printName":function(){
alert(this.name);
}}
person.printName(); //defaultname
person.setName("newName" );
person.printName(); //newName
var person = {name:"defaultname",
setName:function(s){
this.name = s;
} ,
"printName":function(){
alert(this.name);
}}
person.printName(); //defaultname
person.setName("newName") ;
person.printName(); //newName

In the above example, you can use person.name=.. to directly change the name attribute of person. Here we are just for Show what you just mentioned.
Another way to change the person attribute is to define a function that receives two parameters, one is person and the other is the value of name, which looks like this:
changeName (person, "newName"). Which method is better? Obviously, the method in the example is more vivid and intuitive, and it seems to be a little bit oriented to the
object.

Emphasis again For a moment, the method itself is a function, but the use of the method is more restricted. In the following pages, if a function is mentioned, then the content mentioned in
also applies to the method, but not vice versa. .

Prototype attribute of function
Each function contains a prototype (prototype) attribute, which forms the core basis of object-oriented JavaScript. We will discuss it in detail later.
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