Basic knowledge of JS (2)

Data types in JS

  1. Basic data types: String (string), Number (value), Boolean (Boolean), Null (empty value), Undefined (object)

  2. Complex data type: Object (object)

Using the data of the basic data type, the variables created are independent and cannot be integrated. Therefore, the concept of object is introduced. The object belongs to the composite data type, and multiple attributes of different types can be stored in the object.

object

object classification

Built-in objects:

  • Objects defined in the ES standard can be used in any ES implementation;
  • 比如:Math String Number Boolean Function Object…

host object:

  • The objects provided by the JS operating environment mainly refer to the objects provided by the browser at present.
  • For example: BOM DOM

Custom Cashout:

  • Objects created by developers themselves

Object Basic Operations

  • The function called with the new keyword is the constructor. A constructor is a function that is used to create an object
  • When checking an object with typeof, it returns object
  • The values ​​held in an object are called properties
  • Add attributes to the object, syntax: object. attribute name = attribute value
  • Read properties in an object: object.properties
  • Modify the attribute value in the object: object. attribute name = new value
  • Delete the attribute value in the single object: delete object. attribute name
//创建对象
var obj = new Object();
console.log(obj);
obj.name = "孙悟空";
obj.gender = "男";
obj.age = 18;
console.log(obj);
//读取对象的属性
console.log(obj.age);
//修改对象的属性
obj.name = '猪八戒';
//删除对象的属性
delete obj.name

Note: If you read an attribute that is not in the object, no error will be reported, but undefined will be returned

attribute name and attribute value

  • The attribute name of the object is not mandatory to comply with the specification of the identifier, that is to say, there can be an attribute name called var, but try not to use it
  • If you want to use a special attribute name, you cannot use the method of ., such as 123 attribute name, but you need to use another method: Syntax. Object["Attribute Name"] = attribute valueobj["123"] = 789; console.log(obj["123"]);
  • Using [ ] to operate attributes is more flexible. In [ ], a variable can be passed directly, so that the value of the variable will read that attribute equivalent var n = '123'; console.log(obj['123'])toconsole.log(obj[n])
  • The attribute value can be any data type, even an object

in operator

Through this operator, you can check whether an object contains the specified attribute, and return true if it exists, and false if it does not.

Check whether obj contains test2 attribute.

console.log("test2" in obj)

Primitive data types and reference data types

  1. Basic data types: String (string), Number (value), Boolean (Boolean), Null (empty value), Undefined (object)
  2. Reference data type: Object (object)

The difference between primitive data types and reference data types

The values ​​of the basic data types are all stored in the stack memory, and the values ​​exist independently. Modifying one variable will not affect other variables.

var a = 123;
var b = a;
a++
console.log(a); //输出值为:124
console.log(b)  //输出值为:123

The reference data type is stored in the heap memory. Every time a new object is created, a new memory space will be opened in the heap memory. The variable holds the memory address of the object (the reference to the object). If two variables hold the same object reference, when the property is modified through one variable, the other will also be affected.

Take the following example as an example. The variables obj1 and obj2 are stored in the stack memory. The variables stored in the variables only point to the address of the memory space opened for the object in the heap memory, which is equivalent to a pointer. The two variables point to the memory in the same heap memory. The address of the space changes the properties of the objects in the heap memory; therefore

var obj1 = new Object();
obj1.name = '孙悟空';
var obj2 = obj1;
obj1.name = '猪八戒';
console.log(obj1);  //输出值为:猪八戒
console.log(obj2);  //输出值为:猪八戒

When obj2 is set to null: At this time, the pointer of obj2 is null, and the pointer of obj1 still stores the address of the memory space in the heap memory pointing to the object.

var obj1 = new Object();
obj1.name = '孙悟空';
var obj2 = obj1;
obj1.name = '猪八戒';
onj2 = null;
console.log(obj1);  //输出值为:Object
console.log(obj2);  //输出值为:null

Basic data types:

var a = 10;
var b = 10;
console.log(a==b);//输出true

Reference data type: Every time an object is new (created), a new space will be opened up in the heap memory, so the object is created twice, and the space occupied each time is different. The space addresses stored in the obj1 and obj2 variables are not the same, so the two objects are not equal.

var obj1 = new Object();
var onj2 = new Object();
obj1.name = '沙和尚';
obj2.name = '沙和尚';
console.log(obj1 == obj2);//输出false

Summarize:

  1. Comparing values ​​when comparing values ​​of two primitive data types;
  2. When comparing two reference types, the memory address of the object is compared. If the two objects are exactly the same but have different addresses, false will also be returned;

object literal

A method to create an object:

  1. Use the new keyword (constructor way):var obj = new Object()
  2. Use an object literal to create an object:var obj1 = {}; var obj2 = {name:'猪八戒',age:28}

The attribute name of the object literal can be quoted (because the attribute name itself is a string), or not, it is recommended not to add, if you want to use a special name, you must add quotes

var obj2 = {
    
    
	name:'猪八戒',
	age:28
}
等同于
var obj2 = {
    
    
	'name':'猪八戒',
	'age':28
}

function

  • A function is also an object
  • Some functions (code) can be encapsulated in the function, and these functions can be executed when needed ()
  • When checking a function object with typeof, it returns function()

Create a function object:

  • Create function objects with a constructor:var fun = new Function()
  • Create a function using a function declaration: function 函数名([形参1,形参2...形参N]){ 语句...}; where [] means optional.
  • Use function expressions to create a function: var 函数名 = function([形参1,形参2...形参N]){语句...}, the so-called function expression is to create an anonymous function and assign the anonymous function to a variable

function parameters

  • One or more formal parameters can be specified in () of the function, separated by , between multiple formal parameters, declaring the formal parameters is equivalent to declaring the corresponding variables inside the function , but not assigning valuesfunction sum(a,b){ console.log(a+b);}
  • When calling a function, you can specify an actual parameter in (), and the actual parameter will be assigned to the corresponding parameter in the function.sum(1,2)
  • When the function is called, the parser will not check the type of the actual parameter, and the actual parameter of the function can be of any data type, so pay attention to whether it is possible to receive illegal parameters, and if possible, it is necessary to check the type of the parameters
  • When calling a function, the parser will not check the number of actual parameters, and redundant formal parameters will not be assigned; if the number of actual parameters is less than the number of formal parameters, the formal parameters without corresponding actual parameters will be undefined

function return value

function sum(a,b,c){
    
    
	var d = a + b + c;
	return d;
	alert('hello');
}
var result = sum(1,2,3)
  • Statements after return will not be executed, so alert will not be executed
  • If the return statement is not followed by any value, it is equivalent to returning an undefined
  • If return is not written in the function, it will also return undefined

The actual parameter can be any data type or an object . When we have too many parameters, we can encapsulate the parameters into an object and pass them through the object

function sayHello(name.age,gender,address){
    
    
	console.log("我是"+name,"我今年"+age+"岁了""我是一个"+gender+"人""我住在"+address);
}
sayHello("猪八戒",28,"高老庄","男");
function sayHello(o){
    
    
	console.log("我是"+o.name,"我今年"+o.age+"岁了""我是一个"+o.gender+"人""我住在"+o.address);
}
var obj = {
    
    
	name:'猪八戒',
	age:28,
	gender:'男'
	address:'花果山'
};
sayHello(obj);

The argument can also be a function (since a function is essentially an object)

In the following example, a function sayHello is passed to fun as an actual parameter. At this time, a=function sayHello(o){...}, in other words, a is equal to the sayHello function.

function fun(a){
    
    
	console.log('a='+a);
}

function sayHello(name.age,gender,address){
    
    
	console.log("我是"+name,"我今年"+age+"岁了""我是一个"+gender+"人""我住在"+address);
}

fun(sayHello);

area() and area

area(): call function
area: function object

function area(r){
    
    
    return  3.14 * r * r;
}
function fun(a){
    
    
	console.log('a='+a);
}
fun(area)//相当于把area这个对象赋给了a,所以输出就为:a = function fun(a){console.log('a='+a);}
fun(area(10))//相当于把函数的返回值作为参数传给a,因此输出为:a=314

fun(area) is equivalent to assigning the area object to a, so the output is: a = function fun(a){console.log('a='+a);}
fun(area(10)) is equivalent to Pass the return value of the function as a parameter to a, so the output is: a=314 For
example: fun(area) is equivalent to giving the ice cream machine to the other party, and fun(area(10)) is equivalent to giving the ice cream to the other party

return

  • break can exit the current loop
  • continue is used to skip the current cycle
  • return can end the entire function

anonymous function

A function without a name is called an anonymous function. Writing an anonymous function directly in the code will report an error. If you add a parenthesis to it outside to indicate that it is a whole, no error will be reported. So for anonymous functions, how to call it?

The general way to call a function: function object (). The anonymous function as a whole is a function object, but no variables are used to receive it, and the function object does exist, so you only need to add parentheses after it. Such a function is called an immediate execution function: after the function is defined , immediately Called, immediate execution functions are often only executed once.

(function(){
    
    
 	alert('我是一个匿名函数');
})();

(function(){
    
    
	console.log("a=" + a);
	console.log("b=" + b);
})(123,456);
输出a=123  b=456

method

The attribute value of an object can be any data type, or it can be a function

var obj = new Object();
//向对象中添加属性
obj.name = '孙悟空';
obj.age = 18;
obj.sayName = function(){
    
    
	console.log(obj.name);
}
obj.sayName();

If a function is stored as a property of an object, then we call the function a method of the object, and calling a function is called a method of the object. So sayName is the method of obj, and when sayName is called, it is called the method of calling obj's sayName. It's just a difference in name, there is no essential difference.

properties in an enumeration object

for...in statement: There are several attributes in the object, and the loop body will be executed several times. Each time it is executed, the name of an attribute in the object will be assigned to the variable n, so n is name, age, gender, address.

var obj = {
    
    
	name:'孙悟空',
	age:18,
	gender:'男',
	address:'花果山'
};
for(var n in obj){
    
    
	console.log('属性名:'+n)
	console.log('属性值:'obj[n]);
}

scope

Scope: refers to the scope of a variable

  1. Global scope:
    The JS code directly written in the script tag is in the global scope. The
    global scope is created when the page is opened and destroyed when the page is closed.
    There is a global object window in the global scope, which represents a browser The window, created by the browser, we can use directly.
    In the global scope: the variables created will be saved as properties of the window object. var a=10;console.log(window.a) //10,
    in the global scope: the created function will always be saved as a method of the window object function fun(){console.log('我是fun函数');} window.fun()
    Variables in the global scope are global variables, which can be accessed in any part of the page

  2. Variables are declared ahead of time:

    console.log("a ="+a); var a = 123Variables declared with the var keyword will be declared equivalent to undefined before all code is executed var a; console.log("a ="+a); a=123;; if the variable is declared without the var keyword, the variable will not be declared in advance.

  3. Function declaration in advance:
    the function created using the function declaration form: function function name (){}, it will be created before all codes are executed, so the function can be called before the function declaration. However, the function created by using the function expression just declares the variable in advance, and the value of the variable is undefined. Therefore, the function cannot be called before the function is created by the function expression.

Function declaration: (no error will be reported)

fun();
function fun(){
    
    
	console.log("我是一个fun函数");
}

Function expression: (will report an error)

fun();
var fun = function(){
    
    
	console.log("我是一个fun函数"}
  1. Function scope
    Create a function scope when calling a function, after the function is executed, the function scope is destroyed
    Every time a function is called, a new function scope will be created, they are independent of each other, and
    the global scope can be accessed in the function scope Variables in the scope, and variables in the function scope cannot be accessed in the global scope.
    When operating a variable in the function scope, it will look for it in its own scope. If there is one, it will be used directly without going up Level scope until the global scope is found, if the global scope is still not found, it will report an error ReferenceError (reference exception)
    If you want to directly access the global scope in the function, add window directly before the variable, (window .a)
    There is also the feature of early declaration in the function scope. Variables declared with the var keyword will be declared before all codes in the function are executed, and function declarations will also be executed in the function before all codes in the function are executed. Do not
    use Variables declared by var will become global variables.
    Defining formal parameters is equivalent to declaring variables in the function scope.
var e = 23;
function fun(e){
    
    
//相当于 var e;
	alert(e)
}
fun()

output undefined

this

Every time the parser calls a function, it will pass an implicit parameter into the function: this; this is essentially a parameter, which is the same as the actual parameter passed in when we call the function, except that this is passed in by window of. This points to an object, which we call the context object of function execution ; depending on the function calling method , this will point to different objects

function fun(a,b){
    
    
	console.log("a = "+a+", b = "+b);
	console.log(this)//输出全局对象window
}
fun(123,456)
function fun(){
    
    
	console.log("a = "+a+", b = "+b);
	console.log(this)//输出全局对象window
}
var obj = {
    
    
	name:'孙悟空',
	sayName:fun
}
console.log(obj.sayName == fun)//true
obj.sayName();//obj对象
fun();//Window对象

When calling in the form of a function, this is always window; when calling in the form of a method, this is the object that calls the method

var name = '全局'function fun(){
    
    
	console.log(this.name);
}
var obj1 = {
    
    
	name:'孙悟空',
	sayName:fun
}
var obj2 = {
    
    
	name:'沙和尚',
	sayName:fun
}

Summarize:

  • When called as a function, this is window
  • When called as a method, whoever calls the method this is who
  • When called as a constructor, this is the newly created object

Create objects using factory methods

function creatPerson(name,age,gender){
    
    
	//创建一个新的对象
	var obj = new Object();
	//向对象中添加属性
	obj.name = name;
	obj.age = age;
	obj.gender = gender;
	obj.sayName = function(){
    
    
	 alert(this.name)
	};
	//将新的对象返回
	return obj
}
var obj1 = createPerson('孙悟空',28,'男');
var obj2 = createPerson('猪八戒',23,'男');
var obj3 = createPerson('沙和尚',18,'男');
obj3.sayName();//沙和尚

Constructor

The objects created by using the factory method use the constructors of Object, so the objects created are all of type Object, which will make it impossible to distinguish between different types of objects, for example: creating a person and creating a dog are both Object objects; Hence the need for the constructor

A constructor is an ordinary function, and its creation method is the same as that of an ordinary function. The difference is that the first letter of the constructor is customarily capitalized. The difference between a constructor
and an ordinary function is that the calling method is different. Ordinary functions are called directly, while constructors need to be used new keyword to call

function Person(){
    
    
  alert(this);//this就是新建的对象per2
}
//普通函数调用
var per1 = Person();
console.log(per1);//输出undefined,因为per1接受的是函数Person()的返回值,而Person()没有返回值,所以undefined

//构造函数调用
var per2 = new Person();
console.log(per2);//输出Person(对象)

The execution flow of the constructor:

When calling a constructor:

  1. Immediately create a new object: use the new keyword to open up a new space in the heap memory to create the object
  2. Set the newly created object as this in the function, and this can be used in the constructor to refer to the newly created object
  3. Execute the code in a function line by line
  4. Return the newly created object as the return value
function Person(name , age , gender){
    
    
	this.name = name ;
	this.age = age ;
	this.gender = gender ;
	this.sayName = function(){
    
    
		alert(this.name);
	}
}

function Dog(){
    
    
}

//构造函数调用
var per1 = new Person('孙悟空',28,'男');
var per2 = new Person('猪八戒',23,'男');
var per3 = new Person('沙和尚',18,'男');
console.log(per1);
console.log(per2);
console.log(per3);

var dog = new Dog()

Objects created using the same constructor are called a class of objects, and the constructor is also called a class. The objects we create through a constructor are called instances of the class. As above: per1 is an instance of the Person class, and dog is an instance of the Dog class.

instanceof: You can check whether an object is an instance of a class; Syntax: 对象 instanceof 构造函数; Return true if it is, otherwise return false

All objects are descendants of Object, so any object and Object will return true when instanceof checks console.log(dog instanceof Object): true.

Constructor modification:

In the Person constructor, a sayName method is added to each object. Once the constructor is executed, a new sayName method will be created, which means that the sayName of all instances is unique, which will lead to the creation of a new method when the constructor is executed once, and 10,000 instances will be created when executed 10,000 times. new method, and 10,000 methods are the same, which is unnecessary.

//创建一个Person的构造函数
function Person(name , age , gender){
    
    
	this.name = name ;
	this.age = age ;
	this.gender = gender ;
	//向函数中添加一个方法
	this.sayName = function(){
    
    
		alert("大家好,我是"+this.name);
	}
}

var per1 = new Person('孙悟空',28,'男');
var per2 = new Person('猪八戒',23,'男');

per1.sayName();
per2.sayName()

console.log(per1.sayName == per2.sayName);//false:调用的是每个对象创建的每个相应的方法

Since it is the same method, but it is called by different objects, then the method can be defined in the global scope

//创建一个Person的构造函数
function Person(name , age , gender){
    
    
	this.name = name ;
	this.age = age ;
	this.gender = gender ;
	//向函数中添加一个方法
	this.sayName = fun;
}

//将sayName方法在全局作用域中定义
function fun(){
    
    
	alert("大家好,我是"+this.name);
}

var per1 = new Person('孙悟空',28,'男');
var per2 = new Person('猪八戒',23,'男');

per1.sayName();
per2.sayName();

console.log(per1.sayName == per2.sayName);//true,调用的是同一个方法

prototype object

Defining a function in the global scope will pollute the namespace of the global scope, and it is not very safe to define it in the global scope. If multiple people develop, it is easy to have duplicate names, so try not to use it in the global scope. define function

Prototype prototype: For the functions we create (all functions), the parser will add an attribute prototype to the function. Each function has its own prototype property, which corresponds to an object, which is what we call a prototype object. If the function is called as an ordinary function, prototype has no effect; if the function is called as a constructor, there will be an implicit property in the object he creates, which points to the prototype object of the constructor, and we can access it through __proto__ the property

function MyClass(){
    
    
}
var mc = new MyClass();
console.log(MyClass.prototype);
console.log(mc.__proto__);
console.log(mc.__proto__ == MyClass.prototype);//true

insert image description here
The prototype object is equivalent to a public area . All instances of the same class can access this prototype object. We can uniformly set the common content in the object to the prototype object.
When we access a property or method of the object, it It will be found in the object itself, if there is, it will be used directly, if not, it will be searched in the prototype object, if found, it will be used directly

function MyClass(){
    
    
}
//向MyClass的原型中添加属性a
MyClass.prototype.a = 123
//向MyClass的原型中添加一个方法(与属性一样的道理)
MyClass.prototype.sayHello = function(){
    
    
	alert('Hello');
}
var mc = new MyClass();
var mc2 = new MyClass();
console.log(mc.a);//123

insert image description here

function MyClass(){
    
    
}
MyClass.prototype.a = 123
var mc = new MyClass();
var mc2 = new MyClass();
//向mc中添加a属性
mc.a = '我是mc中的a'
console.log(mc.a);//我是mc中的a
console.log(mc2.a);//123

insert image description here
Therefore, the code modified by the constructor in the previous section can be optimized into the following form:

function Person(name , age , gender){
    
    
	this.name = name ;
	this.age = age ;
	this.gender = gender ;
}

Person.prototype.sayName = function (){
    
    
	alert("大家好,我是"+this.name);
};

var per1 = new Person('孙悟空',28,'男');
var per2 = new Person('猪八戒',23,'男');

per1.sayName();
per2.sayName();

This form is more flexible. If per2 does not need or is different from the display of the sayName method, you only need to create a sayName method that you need in your own interior.

When using in to check whether there is a property in the object, if it is not in the object but it is in the prototype, it will also return true. You can use the object's hasOwnProperty() to check whether the object itself contains the property

function MyClass() {
    
    
}
MyClass.prototype.name = '我是原型中的名字';
var mc = new MyClass();
console.log('name' in mc) //true
console.log(mc.hasOwnProperty('name'))//false

So where is hasOwnProperty()?

console.log(mc.hasOwnProperty('hasOwnProperty'));//false,不在mc中
console.log(mc.__proto__.hasOwnProperty('hasOwnProperty'));//false,不在MyClass的原型中

A prototype object is also an object, so it also has a prototype

console.log(mc.__proto__.__proto__.hasOwnProperty('hasOwnProperty'));//true

Therefore, the hasOwnProperty() method is in the prototype of the MyClass prototype. In the
insert image description here
prototype object
, when we access a property or method of the object, it will be found in the object itself. If there is one, it will be used directly. If not, it will be searched in the prototype object. If found, use it directly, if not, go to the prototype of the prototype to search until you find the prototype of the Object object, the prototype of the Object object has no prototype, if it is still not found in the Object, then return undefined

garbage collection

Garbage will also be generated during the running of the program. After the accumulation of too much garbage, the speed of running the program will be too slow. Therefore, we need a garbage collection mechanism to deal with the garbage during the running of the program.

When an object does not have any variables or properties to refer to it, we will not be able to manipulate the object at this time, then this object is a garbage. Too many such objects will take up a lot of memory space, causing the program to run slower. Therefore, this garbage must be cleaned up. There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory, and we do not need and cannot perform garbage collection operations. All we need to do is set the unused objects to Null.

var obj = new Object();
obj = null;

Guess you like

Origin blog.csdn.net/weixin_48242257/article/details/121105442