(E) a reference type

Before writing the article

Bloggers introductory programming student of c, so some concept also turn, however, the first non-js language to understand the next classes, objects and instances

Class is a collection of a group of objects, which contains a number of N objects. The object is just a special case of class.

To say "An Beibei" is a dog, it's just a special case of dogs (and it is not the same as other dogs, it's hair color, weight, length, and some attribute to determine that it is in dogs only), and therefore we call it a specific object.

new role:

  • Create an object, instantiate an object
  • Instantiating the object, given the object space, i.e. the heap memory address
  • Call the constructor

In short: each object (Object) is an instance of a class (Class) of (Instance)

In this chapter

  • user target audience
  • Create and manipulate arrays
  • Understand the basic types of JavaScript
  • Use basic types and basic package types

Emphasis

Array set of methods, Date methodologies
function: this, prototype, apply (), and call (), bind ()

text

Key stroke: the value of reference type (object) is a reference type (class) of an instance
in ECMAScript, reference type is a data structure for data and functions organized together. It is also often referred to as category, but this title is not appropriate. Although ECMAScript is an object-oriented language technically, but it does not have the basic configuration of classes and interfaces of traditional object-oriented support. They are not figured concept, so this is no longer using the class concept.
Reference type sometimes referred to as object definition because it is a class of objects have their properties and methods described herein.

var person = new Object()

This line of code creates a new instance of Object reference type, then save the instance variables in person. When using the constructor Object, only it defines the default properties and methods for the new object. ECMAScript provides many native reference type (eg Object), so developers to achieve common computing tasks.

A, Object Type

So far, we have seen most of the reference types are instances of type Object; and Object is the most used type of a ECMAScript, although an instance of Object does not have much function, but in dealing with the storage and transmission of data, it is a very ideal choice.

create

a new

var person = new Object();
person.name = "Nicholas",
person.age = 18

Object literal syntax, to ease the process of creating an object that contains a large number of properties. By its definition of the object, in fact, it does not call the Object constructor.

: Attribute name can also use the string "name":"Nicholas"will automatically be converted to a string, and the value of the property name

//对象字面量语法
var person = {
    name:"Nicholas",
    age:18//不能添加逗号,ES6中可以
}

access

Dot notation

//点表示法
person.name

Bracket notation

The advantage is variable can be accessed through the property, if the property name contains characters will cause a syntax error, or if you use keywords or reserved words, you can also use this method

//括号表示法
var propertyName = "name"
person[propertyName]
person["first name"]  //含有铬空格,不能用点表示法来访问

Two, Array type

ECMAScript each array can store any type of data, and the size of the array can be dynamically adjusted.

Create and access

When using array literal notation also does not call the Array constructor. (Except Firefox3 and earlier)

//new一个
var colors = new Array();
var colors = new Array(3);
var colors = new Array("red","blud","green");
var colors = Array()

//数组字面量表示法
var colors = ["red","blud","green"];
var colors = [1,2,];   // × 不要这样,会创建一个包含2或3项的数组 
colors[0]   //red

Using the length

Easily add new items to the end of the array

colors[colors.length] = "black"

Array.isArray()

Detection issues into an array:
the instanceof operator assumes its single global execution environment. If the page contains a plurality of frames, actually there are two or more different global execution environment, so that the presence of two or more different versions of the Array constructor. If you pass an array from one frame to another frame, and then the incoming array in the second frame natively create arrays each have their different constructors. How to solve it?

ECMAScript5 new Array.isArray (array). This approach ultimately determine a value in the end is not an array, regardless created in which global execution environment.

Array Methods

Supplementary:
.some () if there is an element satisfies the condition, the expression returns true, the remaining elements will not perform detection.

.slice () does not change the original array

Reduction method: reduce () and reduceRight, all phases Both methods iterative array, and then build a final value is returned.

var values = [1,2,3,4,5]
var sum = values.reduce(function(){
    return prev + cur;
});
alert(sum)  //15

sort () to add

.sort () in order to achieve the sort, calls toString each item in the array () the transformation method, and then the resulting string comparison.

var value = [0,1,5,10,15]
value.sort(),
values //0,1,10,15,5

If you want to be sorted by other criteria, it is necessary to provide a comparison function, a function to compare the two values, and then returns a number for explaining the relative order of these two values.

❗ ❗ not get to know the inner workings of

//升序
function compare(value1,value2){
    if(value1 < value2){
        return -1;   //想要value1位于value2之前,则返回负数
    }else if(value1 > value2){
        return 1;    //想要value1位于value2之后,则返回正数
    }else{
        return 0;
    }    
}

var value = [0,1,5,10,15]
value.sort(compare),
values //0,1,5,10,15

For value type or a valueOf () method returns the object type of numeric types, you can use a more simple comparison function:

//升序
function compare(value1,value2){
    return value2-value1
}

Three, Date type

new Date()

Parameter () in the new Date or not, or is the number of milliseconds date (January 1970 beginning at midnight on the 1st), Date.parse () and Date.UTC () can.

var myDate = new Date();   //2020-03-28T09:32:11.510Z
//Date.parse()和Date.UTC()
var myDate = new Date(Date.parse("May 25,2004"));  //2004-05-24T16:00:00.000Z
var myDate = new Date("May 25,2004");  
var myDate = new Date(Date.UTC(2000,0));  
var myDate = new Date(Date.UTC(2000,4,5,17,55,55)); //2000-05-05T17:55:55.000Z
//基于本地时区
var myDate = new Date(2000,0);
var myDate = new Date(2005,4,5,17,55,55)

Date.now()

//取得开始时间
var start = Date.now()

doSomething()

//取得停止时间
var stop = Date.now()

Inherited methods

Like other reference types, Date also rewritten toLocaleString (), toString () and value () method. However, these methods return values ​​different from other types of methods. The output of these methods are different depending on the browser

var myDate = new Date()
alert(myDate.toLocaleString())  //2020-3-28 18:05:38
alert(myDate.toString())  //Sat Mar 28 2020 18:05:38 GMT+0800 (GMT+08:00)
alert(myDate.valueOf())  //1585389938346

Date Format

The output of these methods vary depending on the browser.
toDateString () display the day of the week, month, day, and year in the format implemented in particular;
toTimeString () to a specific display in format to achieve, minutes, seconds and time zone
toLocalDateString () display the day of the week, month to locale-specific format , day, and year
toLocalTimeString () to display in a particular format to achieve, minutes, seconds
toUTCString () specific to the full realization of UTC date format

Common method

myDate.getYear (); // Get the current year (2) 
myDate.getFullYear (); // get the full year (4, 1970 - ????) 
myDate.getMonth (); // Get the current month ( 0-11,0 representatives in January), so to get the current month is myDate.getMonth () + 1;  
myDate.getDate (); // get the current day (1-31) 
myDate.getDay (); // get the current week X (0-6,0 for Sunday) 
myDate.getTime (); // get the current time (number of milliseconds from the start 1970.1.1) 
myDate.getHours (); // Get the current hour (0-23) 
myDate. getMinutes (); // get the current number (0-59) minutes 
myDate.getSeconds (); // get the current number of seconds (0-59) 
myDate.getMilliseconds (); // get the current number of milliseconds (0-999) 
myDate .toLocaleDateString (); // get the current date

Regex type

Positive about the use of regular expressions in JavaScript, it is recommended to see "JavaScript regular expression mini-book", after reading it again I would do a detailed summary.
Here is not too many notes.

create

var expression = /pattern/flags

pattern : can be any simple or complex regular expression
flags : grepresents the global, not found immediately stop when the first match; irepresents not case-sensitive; mrepresents a multi-line mode, a line of text that is reaching the end of Shihai back continue Find the next line

Instance Properties

constructor returns a function, which is to create a RegExp object's prototype.
determining whether a global "g" modifier
ignoreCase determines whether a "i" modifier
lastIndex predetermined starting position for the next match for
"m" modifier determines whether a multiline
source returns a regular expression pattern matching

Examples of methods

regex.exec (str) Return value (array) to find and determine a position
regex.test (str) detecting whether a character string matching a pattern
regex.toString () Returns a string of a regular expression

Five, Function

Each instance of type Function is a function, and the other reference types Betta as having attributes and methods. Because when function object, so the function name is actually a pointer to a function object, not tied to a particular function .

create

Function declaration syntax definition

function sum(num1,num2){
    return num1 + num2;
}

Defined function expression

var sum = function (num1,num2){
    return num1 + num2;
};

Parser when loading data into the execution environment, will be the first reading function declarations, and make it accessible before executing any code
as to function expression, Xu Bo, wait until the parser to execute it in the lines of code, will really it is interpreted.

alert(sum());
function sum(){
    //...
}

Understanding the function name is actually a pointer to a function object, look at the following code

function sum(num1,num2){
    return num1 + num2;
}

alert(sum(10,10))  //20

var anotherSum = sum;
sum = null;
alert(anotherSum(10,10))  //20

It does not override (deep understanding)

Chapter Three examples:

function addSomeNumber(num){
    return num + 100;
}

function addSomeNumber(num1,num2){
    return num1 + num2;
}

Contact function name is actually a pointer to the function object, the code can be seen as the following:

function addSomeNumber(num){
    return num + 100;
}

addSomeNumber = function(num1,num2){   //表面上是覆盖原函数,实际是指针指向改变
    return num1 + num2;
}

As a function of the value of

Internal property function

arguments、arguments.callee

The main purpose of arguments that the function arguments, this object also has a callee property called, this property is a pointer to a function that has arguments object. example:

function factorial(num){
    if(num <= 1){
        return 1;
    }else{
        //return num*factorial(num-1)
        return num*arguments.callee(num-1) 
    }
}

In the factorial rewritten this () function in vivo function, and no further reference to the function name factorial. In this way, regardless of what name when referencing function, can guarantee the normal completion of recursive calls.

this

this is a function of reference data on the object to the environment - or it can be said that this value (when calling a function in the global scope of the page, this is the object reference window). Example:

window.color = "red"
var o = {color: "blue"}

function sayColor() {
    alert(this.color)
}

sayColor();  //red

o.sayColor = sayColor;
o.sayColor();  //blue

Keep in mind: the name of the function pointer is just a variable that contains it. Therefore, even when performed in different environments, global sayColor () function and o.sayColor () is still pointing to the same function.

caller

This property holds the current function of a function Yong edge of reference. If the current function is invoked in the global scope, it is null.

Function Properties and Methods

ECMAScript is a function of the object, and therefore have attributes and methods. Each function contains two properties: length and prototype. Wherein, length property represents the number of desired functions named parameters received.

length

prototype

In all of the attributes defined in ECMAScript core, the most intriguing of the necessary number of prototype property.

For ECMAScript is a reference type, prototype is to save them all instances where the real methods. Such as toString () and valueOf () methods are actually stored in the prototype name, but each instance of access to the object by Bale.

When you create a custom reference types and inheritance, prototype property is extremely important. (Detail in Chapter 6)

In the ECMAScript5, prototype property is not enumerable, the use of for-in can not be found.

apply () and call ()

Each function contains two methods of non-inherited: apply () and call (). The use of these two methods are called function specific domain effect , substantially equal to the set value of this object function in vivo.

First, Apply () method takes two parameters: a scope in which the function is running, the other is a parameter array. Wherein the second parameter is an instance of Array, arguments may be objects. E.g:

function sum(num1,num2){
    return num1 + num2;
}

function callSum1(num1,num2){  //传入arguments对象
    return sum.apply(this,arguments)
}

function callSum2(num1,num2){
    return sum.apply(this,[num1,num2])  //传入数组
}

alert(callSum1(10,10))  //20
alert(callSum2(10,10))  //20

In this example, callSum1 () was introduced to this as this value when performing sum () function (because it calls global scope, it is passed in the window object), and the arguments object.

call () method with the same function apply () method of embodiment differ only accepts parameters. call () method first parameter is the value of this difference is that the remaining parameters are directly passed to the function. That is passed to the function must be individually listed. example:

function sum(num1,num2){
    return num1 + num2;
}

function callSum1(num1,num2){  //传入arguments对象
    return sum.call(this,num1,num2)
}

alert(callSum1(10,10))  //20

They really powerful place to be able to expand the function to run a scope, advantage is that there is no coupling relationship between objects and methods is not required. example:

window.color = "red"
var o = {color:"blue"}
function sayColor(){
    alert(this.color)
}
sayColor()  //red
sayColor.call(this)  //red
sayColor.call(window)  //red
sayColor.call(o)  //blue

bind()

This method creates an instance of a function, which is bound to the value of this value is passed to bind () function. example:

window.color = "red"
var o = {color:"blue"}
function sayColor(){
    alert(this.color)
}
var objectSayColor = sayColor.bind(o)
objectSayColor()  //blue

Here, sayColor () call to bind () and pass in the object, creating a objectSayColor () function. objectSayColor () this function is equal to the value of o, so even call this function in the global scope, will also see the "blue".

Inherited methods

toLocaleString () and toString () method always returns a function code.

Supplementary: toString () method returns the function code itself, and previous annotations whitespace will be omitted. ES6 will not start up

Guess you like

Origin www.cnblogs.com/L-xmin/p/12587583.html
Recommended