Object part
Object type
Object is an unordered collection that can store objects of any type, and all other objects are inherited from this object.
There are two types of Object creation, one is to use the new operator and the other is literal notation.
1. Create an Object using the new operator
var obj = new Object();// Pay attention to capitalization, you can also write it directly as Object()
Note that generating a new object through the new Object() method is equivalent to the literal method obj = {}.
2. Create using literal method:
var obj = { name : 'trigkit4', age : 21};//The semicolon is best to addWhen declaring an Object object using literals, the Object() constructor is not called (except FF)
Object.prototype object
All constructors have a prototype attribute that points to a prototype object.
Object.prototype.print = function(){ console.log(this)};var obj = new Object();obj.print() // ObjectInstance obj directly inherits the properties and methods of Object.prototype
1. Objects are just special data. Objects have properties and methods. JavaScript is an object-oriented language, but JavaScript does not use classes. JavaScript is based on [prototype][1], not class-based.
2. Attribute: It is a variable affiliated to a specific object. Method: It is a function that can only be called by a specific object.
3.js objects are a collection of properties and methods. A method is a function, which is a member of an object. An attribute is a value or a set of values (in the form of an array or object) that is a member of an object.
4.js object is based on the constructor function. When using the constructor function to create a new object, it can be said that a new object is instantiated. Properties are variables inside the constructor function.
Objects instantiated using constructor functions:
cat = new Animal();
Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class (class) in its syntax.
<script type="text/javascript"> //Object is a collection of name/value pairs var browser = { //Object is name enclosed in curly braces:"Firefox", kernel:"Gecko" };</script> // Access the object's attributes browser.name //"Firefox" browser["kernel"] //"Gecko"Objects (objct) are a collection of properties, each property consists of "name/value pairs". js also defines a special object - an array, which is an ordered set of numbered values.
js also defines a special object - a function, a function is an object with executable code associated with it. It executes the code by calling the function and returns the operation result.
There is no class in JS, but it takes a new name called "prototype object", so "class ==prototype object", see: JavaScript class writing method (I)
2. The difference and connection between classes (prototype objects) and objects (instances)
1. Classes (prototype objects) are abstract, conceptual, representing a type of things.
2. The object is concrete, practical, and represents a specific thing.
3. Class (prototype object) is a template for object instances, and object instances are individuals of the class.
A common misconception is that the literal value of a number is not an object. This is because of a bug in the JavaScript parser that tries to parse the point operator as part of the floating point numerical face value.
There are many workarounds to make the literal value of a number look like an object.
2..toString(); // The second dot can be parsed normally
2.toString(); // Pay attention to the spaces before the dot
(2).toString(); // 2 is calculated first
Delete attributes
The only way to delete a property is to use the delete operator; setting the property to undefined or null does not really delete the property, but simply removes the association between the property and the value.
Three major features of JavaScript object-oriented
Encapsulation: No internal implementation is considered, only functional use is considered
Inheritance: Inherit a new object from an existing object
Polymorphism: The so-called polymorphism refers to multiple states that refer to in different situations.
1. Packaging
Encapsulation means to group the commonalities (including attributes and behaviors) of things belonging to the same category into a class for easy use. For example, the human thing can be encapsulated in the following ways:
people{
Age (attribute 1)
Height (attribute 2)
Gender (attribute three)
Do things (one of the behaviors)
Walking (behavior 2)
Speaking (act 3)
}
Benefits of encapsulation:
Encapsulation protects the integrity of internal data;
Encapsulation makes refactoring of objects easier;
Weaken coupling between modules and improve the reusability of objects;
Helps avoid namespace conflicts;
See the following example:
<script type="text/javascript"> var boy = {}; //Create an empty object boy.name = "Xiao Ming";//Assign boy.age = 12 according to the properties of the prototype object, var girl = {}; girl.name = "Xiaohong"; girl.age = 10; </script>This is the simplest encapsulation, encapsulating two attributes in one object. However, this writing method has two disadvantages. One is that if you generate more instances, it will be very troublesome to write; the other is that there is no way to tell whether there is any connection between the instance and the prototype.
Constructor mode
To solve the problem of generating instances from prototype objects, Javascript provides a constructor pattern.
The so-called "constructor" is actually an ordinary function, but this variable is used internally. Using the new operator for the constructor can generate an instance, and this variable will be bound to the instance object.
For example, the prototype objects of boy and girl can be written like this now:
<script type="text/javascript"> function Person(name,age){ this.name = name; this.age = age; }</script>We can now generate instance objects.
<script type="text/javascript"> var boy = new Person("Xiao Ming",12); var girl = new Person("Xiao Hong",10); alert(boy.name); //Xiao Ming alert(boy.age); //12</script>At this time, boy and girl will automatically contain a constructor attribute pointing to their constructor.
alert(boy.constructor == Person); //true
alert(girl.constructor); //Output the entire string of constructor code, try it yourself
Prototype pattern Javascript stipulates that each constructor has a prototype attribute pointing to another object. All properties and methods of this object will be inherited by instances of the constructor.
This means that we can directly define those unchanged properties and methods on the prototype object.
<script type="text/javascript">function Person(name,age){ this.name = name; this.age = age;}Person.protype.type = "human";Person.protype.eat = function(){ alert("Eat rice");}</script>Then, generate the instance:
<script type="text/javascript">var boy = new Person("Xiao Ming","12");var girl = new Person("Xiao Hong","10");alert(boy.type);//Human boy.eat();//Eat</script>At this time, the type attributes and eat() methods of all instances are actually the same memory address, pointing to the prototype object, thus improving the operation efficiency.
alert(boy.eat == girl.eat); //true
A prototype property is a built-in property that specifies the constructor function that the object extends.
The following code adds a new attribute size to the Animal constructor function, which is the prototype attribute of the cat object. By using prototype properties, all objects extending Animal constructor functions can access the size property
cat = new Animal("feline","meow", "walk/run");cat.prototype.size = "fat";In this case, the size attribute of all Animal objects is "fat". The prototype defaults to a new instance of Object. Since it is still an object, new attributes can be added to the object. Just like style is an object in javascript, you can also continue to add properties after style.
<script type="text/javascript"> /*Define a Person class*/ function Person(_name,_age,_salary){ //The public attribute of the Person class, the public attribute of the class is defined as: "this.property name" this.Name=_name; //The private attribute of the Person class, the private attribute of the class is defined as: "var attribute name" var Age=_age; var Salary=_salary; //Define the public method (privileged method) of the Person class, the public method of the class is defined as: "this.functionName=function(){.....}" this.Show=function(){ alert("Age="+Age+"/t"+"Salary="+Salary);//Accessing the private properties of the class in the public method is allowed}</script>When an object looks for a certain property, it will first traverse its own properties. If not, it will continue to look for the object referenced by [[Prototype]]. If not, it will continue to look for the object referenced by [[Prototype]].[[Prototype]], and so on until [[Prototype]].….[[Prototype]] is undefined (Object's [[[Prototype]] is undefined)
Simply put, it is to save a reference to another object through the object's [[Prototype]], and search the attributes up through this reference. This is the prototype chain.
null object
The function of js assigning null values to variables is:
Assigning a null pointer makes it easy to understand that this variable is prepared to store objects. It's also convenient to adjust the wrong one
Global window object
Any global function or variable in JavaScript is a property of window.
The self object is exactly the same as the window object. Self is usually used to confirm that it is in the current form.
The main main objects of window are as follows:
JavaScript document object
JavaScript frames object
JavaScript history object
JavaScript location object
JavaScript navigator object
JavaScript screen object
Several common methods
valueof() method: Returns the original value of the specified object
The split() method splits the string into a string array and returns this array.
The indexOf() method returns the first occurrence of a specified string value in the string.
The substring() method is used to extract characters in a string between two specified subscripts.
The substr() method extracts the specified number of strings starting from the startPos position from the string.
The join() method is used to put all elements in the array into a string.
arrayObject.join(delimiter)
The reverse() method is used to reverse the order of elements in an array.
The slice() method returns the selected element from an existing array.
Object literal
Object literals are processes used to create a large number of properties, as follows:
<script type="text/javascript"> var company = { name : "Microsoft", ages : 39, employees : 99000, CEO : "Nadella" }; </script>It should be noted here that attributes and attribute values are separated by colons (:); multiple attributes are separated by commas (,). The literal object can also define methods. Just write function on the attributes of this object. This is an anonymous function. You only need to write its method name () to call it.
<script type="text/javascript">var dog = { name:"husky", age:2, run:function(){ return "123";}}alert(dog.run());//If you enter dog.run, the code for the function part behind it will pop up</script>Basic value type wrapper
There are five basic value types in js: number, string, Boolean, null and undefined. Except for null and undefined, the other three have so-called basic wrapping objects. The built-in constructors Number(), String(), and Boolean() can be used to create wrapper objects.
var num = new Number(10);console.log(typeof num);//object Object() method Object() // Return an empty object Object(undefined) // Return an empty object Object(null) // Return an empty object Object(1) // Equivalent to new Number(1)Object('foo')Object(true) // Equivalent to new String('foo')Object(true) // Equivalent to new Boolean(true)Object([]) // Return the original array Object({}) // Return the original object Object(function(){}) // Return the original functionArray part
1.Array object
Array object: Provides support for creating arrays of any data type.
arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])
Definition: var arr = [2,3,45,6]; var arr = new Array(2,4,5,7)
There is no difference in definition between the two, [] has high performance because the code is short.
Use array and object literals: var aTest = []; when creating arrays, using array literals is a good choice; similarly, object literals can also be used to save space. The following two lines are equal, but use the object literals to be shorter:
var oTest = new Object; //Try not to use var oTest = { }; //The best choice, or var 0Test = [ ];Traversal In order to achieve the best performance of traversing arrays, it is recommended to use a classic for loop.
var list = [1, 2, 3, 4, 5, ...... 100000000];for(var i = 0, l = list.length; i < l; i++) { console.log(list[i]);}The above code has a processing, which is to cache the length of the array through l = list.length.
Array constructor
Since Array's constructor is a bit ambiguous when it comes to how to handle arguments, it is always recommended to use the literal syntax of arrays - [] - to create arrays.
Therefore, the following code will be confusing:
new Array(3, 4, 5); // Result: [3, 4, 5]
new Array(3) // Result: [], the length of this array is 3
Try to avoid using array constructors to create new arrays. It is recommended to use the literal syntax of arrays. They are shorter and more concise, thus increasing the readability of the code.
Properties of Array array
Three properties of the Array array: length attribute, prototype attribute, constructor attribute
1.length attribute
The Length attribute represents the length of the array, that is, the number of elements in it. Because the index of an array always starts from 0, the upper and lower limits of an array are: 0 and length-1 respectively. Unlike most other languages, the length property of JavaScript arrays is mutable, which requires special attention.
2.prototype attribute
Returns a reference to the object type prototype. The prototype attribute is common to object.
For Array array objects, use the following example to illustrate the purpose of the prototype attribute.
Add a method to the array object to return the maximum element value in the array. To do this, declare a function, add it to Array.prototype, and use it.
function array_max() { var i,max=this[0]; for(i=1;i<this.length;i++) { if(max<this[i]) max=this[i]; } return max; } Array.prototype.max=array_max; var x=new Array(1,2,3,4,5,6); var y=x.max();After this code is executed, y saves the maximum value in the array x, or 6.
3.constructor attribute
A function that represents the creation of an object. Description: The constructor attribute is a member of all objects with prototype. They include all JScript native objects except Global and Math objects. The constructor property holds a reference to the function that constructs a specific object instance.
For example:
x = new String("Hi"); if(x.constructor==String) //Process (condition is true). //or function MyFunc{ //Func. } y=new MyFunc;if(y.constructor==MyFunc)//process (condition is true).
For arrays:
y = new Array();
Array object method
sort() method
grammar
arrayObject.sort(sortby)
sortby optional. Specify the sorting order. Must be a function.
var arr = [11,2,28,4,5,1];
console.log(arr.sort());//return [1, 11, 2, 28, 4, 5]
Why are the 11 and 28 here not arranged in order? This is because sort without parameters is sorted in character encoding order.
So, what if we want to sort the array elements from small to large? Look at the following code:
var arr = [11,2,28,4,5,1]; console.log(arr.sort(function(a,b){ return ab;//return [1, 2, 4, 5, 11, 28] }));If you want to sort by other criteria, you need to provide a comparison function that compares two values and then returns a number that illustrates the relative order of the two values. The comparison function should have two parameters a and b, and its return value is as follows:
If a is less than b, a should appear before b in the sorted array, then a value less than 0 is returned.
If a is equal to b, return 0.
If a is greater than b, a value greater than 0 is returned.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.