javascript_function

javascript_function

A function is a piece of code that can be reused. It can exist independently and can be used as a class. At the same time, a function is also an object, which itself is a Function instance.

Function definition method

Method 1: Named functions

function 函数名称(形参列表){
    
    代码块;} 

Basic programming implementation

<script>
	//注意: js是弱类型编程语言,所以参数上没有类型,也没有返回值类型
	function sayHello(name){
    
    
		//修改<div id="div1">中的显示内容
		var div1=document.getElementById("div1");
		div1.innerHTML="你好,<strong>"+name+"</strong>!";
		//函数可以有返回值,也可以没有
		return 100;//如果没有返回值,则没有【return 值】的语句,或者【return;】
	}
</script>

<div id="div1">原始显示内容</div>
<!-- 定义一个点击事件触发函数执行,函数不调用则不会执行。onclick属性值为调用函数的语句 -->
<button onclick="sayHello('yanjun')">点击</button>

Method 2: Anonymous function function(形参){代码块;}, and special arrow function provided by ES6

<script>
	var f=function(name){
    
    
		var div1=document.getElementById("div1");
		div1.innerHTML='Hello '+name+"!";
	}
</script>
<div id="div1">原始显示内容</div>
<button onclick="f('yanjun')">点击</button>

Method 3: Use the Function class to define an anonymous functionvar f=new Function("形参列表","具体的代码块");

<script>
	var f=new Function("name", "var
div1=document.getElementById('div1');
div1.innerHTML='hello'+name+'!';")
</script>
<div id="div1">原始显示内容</div>
<button onclick="f('yanjun')">点击</button>

Comparison of the three methods:

  • Function declarations are pre-parsed, and function declarations take precedence over variables
  • The method of using the Function constructor to define a function is a function expression, which will result in two parsing and seriously affect performance. The first time it parses regular JavaScript code, the second time it parses the string passed into the constructor

recursive function

A recursive function is a special function that allows calling its own function within the function definition. For example to calculate the factorial of n,n!=n*(n-1)!

  • It is allowed to return different types of data in different situations in the js function, but this way of writing is generally not recommended
var f=function(n){
    
    
	if(typeof(n)=='number'){
    
    
		if(n==1) return 1;
		else return n*f(n-1);
	}else
		alert('参数类型错误');
}

Calculate factorial of n using recursive calls

<script>
	function jieCheng(num) {
    
    
		alert(num instanceof Number);
		//数据类型的判断可以使用typeof或instanceof两种方式判断
		if ((!(num instanceof Number)) || num < 1) {
    
    
			alert('参数错误!');
			return -1;//返回-1用于表示计算出现错误,当然也可以使用throw new Error("")抛出异常
		}
		if (num == 1) return 1;
		else
			return num * jieCheng(new Number(num - 1));
	}
	
	// var res = jieCheng('5'); 报错 -1加上alert
	var res=jieCheng(new Number('5'));
	alert(res);
</script>

The data type judgment instanceof is incorrect, unless new Number(5), otherwise instanceof is false

<script>
	function jieCheng(num) {
    
    
		if (!(typeof(num)=='number') || num < 1) {
    
    
			alert('参数错误!');
			return -1;//返回-1用于表示计算出现错误,当然也可以使用throw new Error("")抛出异常
		}
		if (num == 1) return 1;
		else
			return num * jieCheng(num - 1);
	}

	// var res = jieCheng('5'); 报错 -1加上alert
	var res=jieCheng(5);
	alert(res);
</script>

The process of writing JS

  • Layout: html+css must ensure a stable layout before writing js, and the layout itself cannot have any compatibility issues
  • Attributes: Determine which attributes to modify Determine which attributes to modify through js, such as display
  • Event: determine what operations the user does (product design) determine what event to modify, such as click, move in and out
  • Write js: In the event, use js to modify the style of the page element
btn1.style.display='block' 将btn1的style的display的值设置为block

get Element By Id 通过id获取元素

<label onmouseover = “document.getElementById(‘btn1’).style.display=‘block’”
onmouseout = “document.getElementById(‘btn1’) .style.display=‘none’“>鼠标经过出现按钮</label>

partial concept

The variables defined in the function are local variables, which are only valid within the scope of the function, and the special problem is the promotion problem.

<script>
	function ff(){
    
    
		var kk=99;
		document.writeln("在ff函数内部调用kk="+kk+"<br/>");
	}

	//首先先调用函数。函数不会主动执行
	ff();
	document.writeln("在函数外部访问函数内的kk="+kk+"<br/>"); //Uncaught ReferenceError: kk is not defined
</script>

Variables defined outside a function are global variables

  • Local variables can only be accessed inside the function, global variables can be accessed in all functions
  • Local variables are destroyed after the function is executed, and global variables are destroyed after the page is closed.

Note: Variables that are not defined using var in a function are also global variables

<script>
	var kk=99;
	function ff(){
    
    
		// kk=100;
		document.writeln("在ff函数内部调用kk="+kk+"<br/>");
	}
	ff();
	document.writeln("在函数外部访问函数内的kk="+kk+"<br/>");
</script>

A local function is a function defined inside a function. For example, if a function inner is defined in an outer function, then inner is a local function, and outer is a global function. The inner local function can be accessed within the outer function, but the inner local function inner cannot be accessed outside the outer function

<script>
	function outer(){
    
    
		function inner(){
    
    
			document.writeln("局部函数111<br/>");
		}
		document.writeln("开始测试局部函数...<br/>");
		inner(); //调用内部局部函数
		document.writeln("结束测试局部函数....")
	}
	
	outer();//调用外部函数

	// 在外部函数之外不能调用内部函数,只能通过外部函数调用内部函数执行
	inner(); //试图调用局部内部函数,内部函数.html:15 Uncaught eferenceError: inner is not defined
</script>

A solution that insists on accessing the inner function outside the outer function:

<script>
	function ff(){
    
    
		var kk=100;//在ff函数内部有效,局部变量
		function show(){
    
     //内部函数,一般外部函数之外不能直接访问
			alert("内部函数中访问内部局部变量:"+kk);
		}
		// show();
		return show; //返回内部函数,从而将show挂在到window对象上
	}

	var p=ff(); //接收ff函数的返回值,从而将p挂在到window对象
	p();//实际上就是调用ff的内部函数show()
	//ff();
	//show();
</script>

Closure

A closure is a function that can read the internal variables of other functions. It is a bridge that connects the interior of the function with the function, even if the external function has been executed.

JavaScript has its own garbage collection mechanism. For functions, after the function is executed, it will be recycled by the garbage collection mechanism to release memory. Local variables inside the function will also be destroyed. Only the global scope can be saved in memory.

<script>
	function ff(){
    
    
		var kk=100;//局部变量,仅仅在ff的范围内有效
	}
	ff();
	document.writeln(kk); //如果访问内部布局变量,则Uncaught ReferenceError: kk is not defined
</script>

In order to directly access the variables inside the function or call the internal functions directly, closures can be introduced to extend the effective range of internal variables

<script>
	function ff(){
    
    
		var kk=100;//局部变量,仅仅在ff的范围内有效
		return kk;
	}

	var p=ff();
	document.writeln(p);
</script>

Reasons for introducing closures

  • Allows external access to variables inside the function
  • Avoid the use of global variables and prevent global variable pollution
  • Let key variables stay in memory and avoid being recycled and destroyed

for internal functions

<script>
	function ff(){
    
    
		function show(){
    
    }
		return show;
	}

	var p=ff();
	p();
</script>

Closure verification

function f1(){
    
    
	var num=999;

	add=function(){
    
    
		num++;
	}
	function f2(){
    
    
		alert(num);
	}
	return f2;
}

var res=f1();
add();//注意add由于没有使用var定义,所以add属于全局的
res();
add();
res();

important point:

  • Since the closure will cause the variables in the function to be saved in memory, the memory consumption will be relatively large, so be careful not to abuse the closure in specific use. The solution is: Before launching the function, delete the local variables that are no longer used
  • Closures change the value of variables inside the parent function outside the parent function. Will affect the encapsulation of the code

global and local conflicts

var sex=true;

function ff(){
    
    
	console.log("ff before:"+sex);
	var sex=123;
	console.log("ff end:"+sex);
}

ff();
alert(sex);

custom class

Mrs. Zhang has two cats: one named Xiaobai, 3 years old, white; the other named Xiaohua, 10 years old, colorful. Write a program that displays the cat's name, age, and color when the user enters the name of the kitten. If the name of the kitten entered by the user is wrong, it will display "Grandma Zhang does not have this cat".

Solve with basic technology

var cat1Name="小白";
var cat1age=3;
var cat1Color="白色";

var cat2Name="小花";
var cat2age=10;
var cat2Color="花色";

Object-oriented technology to solve

//定义猫对象
function Cat(){
    
     }
//定义主人
function Master(){
    
     }

var master1=new Master();
master1.mName="张老太";

//实例化猫
var cat1=new Cat();
//!!特别说明: 在js中,你给它什么成员属性,是自由的.
cat1.cname="小白";
cat1.age=3;
cat1.color="白色";
cat1.master=master1;

var cat2=new Cat();
cat2.dname="小花";
cat2.age=100;
cat2.color="花色";

//访问一下
document.write(cat1.cname+" "+cat1["cname"]+" 它的主人是"+cat1.master["mName"]
);

There are two ways to access an object's exposed properties:

  • object-name.property-name
  • ObjectName['PropertyName']

The difference and connection between class (prototype object) and object (instance)

  • Classes (prototype objects) are abstract, conceptual, and represent a class of things, such as people, cats...
  • Object is concrete, actual, representing a concrete thing
  • A class (prototype object) is a template for an object instance, and an object instance is an individual of the class

properties of the object

The properties of an object are generally basic data types (numbers, strings), or other objects. For example, the age of the cat object created earlier is the property of the cat object

usage of this

  • Variables modified with the this keyword are no longer local variables, they are instance attributes of the function
function Person(name,age){
    
    
	this.name=name; //实例对象每个实例都不同,可以通过new Person("",19).name的方式访问
	Person.nation="汉族"; //类属性,是类的所有实例公用,只能通过Person.nation的方式访问,而不能使用new Person("yan",18).nation方式访问
	var bb=0;//局部变量,外面不能访问,类似局部函数
	cc=123;//全局变量

		this.show=function(){
    
    } //public的成员方法
		Person.bbb=function(){
    
    } //类成员
		abc=function(){
    
    } //全局方法
}

//注意:局部变量在函数执行完毕后销毁,全局变量在页面关闭后销毁,函数内没有使用var声明的变量(需要通过this.的方式)为全局变量

//直接定义一个对象
var p={
    
    
	pp:function(){
    
    
		for(var k=0;k<10;k++)
		document.writeln("慢慢的走...");
	}
}
//调用方式
p.pp();

js is a dynamic language that allows you to add properties and methods to objects at any time. When you directly assign a value to a property of an object, you add properties to the object.

var obj={
    
    }; //使用JSON语法创建一个对象
obj.name='zhangsan'; //向obj对象中添加一个属性name
obj.show=function(){
    
    }; //向obj对象中添加一个成员方法show

Summary: functions, methods, objects, classes

After the function definition in JavaScript, you can get 4 items

  • Function: A function is the same as a method in Java, this function can be called. There is no one-to-one correspondence between formal parameters and actual parameters
<script>
	var f = function (name, age) {
    
    
		alert(name + "-->" + age);
		//可以通过arguments获取所有请求参数
		for(let kk in arguments){
    
    
			document.writeln('参数['+kk+"]="+arguments[kk]+"<br/>");
		}
	}

	f('yanjun',18,23); //实参只有一个,但是形参有2个,实际上传值是从左向右对应,如果缺少则默认传值为undefined
</script>
  • Object: When defining a function, the system will also create an object, which is an instance of the Function class
var f=function(){
    
    }

alert(f instanceof Function);// true 表示f就是Function类型的变量,可以通过f()调用函数
alert(f instanceof Object);// true,表示f是Object类型的变量
alert(f instanceof String);//false,表示f不是String类型

For objects, if you need to understand the core details, you can use console.log(f) to output /console.info

  • Method: When defining a function, this function is usually attached to an object as a method of the object. If it is not specified which object to apply the function to, the function will be attached to the window object as a method of the window object
var f=function(){
    
    }

console.log(window);
window.f();
f();
  • Class: When defining a function, a class with the same name as the function is also obtained, and the function is the only constructor of the class. So in fact, there are two ways to call the function directly and use the new keyword
var f=function(){
    
    
	alert('hello javascript!');
}
//直接调用f();

//使用new运算符创建对象时,会自动执行function()中的定义,function()会当作类的构造器
var ff=new f();
alert(ff);

4 ways to call a function

Method 1: As a function call, the basic syntax is [function name (actual parameter list)]. The function is actually called as a global object, which will make the value of this a global object. Using the window object as a variable will easily cause the program to crash

<script>
	function bb(){
    
    
		this.name="zhangsan";//实际上是将name定义为全局属性
		console.log(this); //输出的应该是window对象
	}

	bb();
	window.bb();
	document.writeln("window.name="+window.name); //证明name称为全局属性
	document.writeln("name="+name);//实际输出和window.name一致
</script>

Method 2: The function is called as a method. When a function is invoked as a method of an object, the value of this will be referred to as the object itself

//使用JSON格式定义对象,JSON的语法格式为{key1:value1,key2:value2...}
var p1={
    
    
	"username":"zhangsan", //定义属性,格式为【属性名:值】
	"age":18,
	show:function(k){
    
    //定义方法,格式为【方法名称:function(形参){}】
		console.log(this);
		document.writeln(k+"---"+this.username+"---"+this.age);
	}
};
//通过对象名.方法名的形式调用show函数
p1.show(12);

Method 3: Use the constructor to call the function, and this in the constructor points to the current object

function Person(){
    
    
	this.name="zhangsan";//定义public属性
	this.age;
	
	this.show=function(){
    
    
		console.log(this);
		document.writeln("name:"+this.name+",age:"+this.age);
	}
}

var p1=new Person(); //则function Person()会自动调用执行
alert(p1.name);//获取p1对象中的name属性值
alert(window.name);//不能获取到数据,因为Person中的this用于指代Person类型对象,不是window对象
p1.show();//调用成员方法

Method 4: Indirect call as a function. There are 3 different ways to implement

classes and objects

After defining the function, you can actually get 4 items

  • function. can be called directly
  • object. Instance of type Function
  • method. Functions are automatically attached to an object
  • kind. A function is the only constructor of a class
//前面已经进行了试验
function Person(name,age){
    
    
	this.name=name; //实例属性,每个实例都不一样,可以通过【对象名.属性名】的方式进行访问

	Person.nation="汉族"; //静态类属性,所有对象共享的属性,只能通过【类型名.属性名】的方式访问
	Person.show = function () {
    
     //静态类成员方法
		console.log(this); //this可以使用,用于指代当前函数
		console.log(this.username); //undefined
		console.log(this.nation); //汉族
	}

	var bb=100; //局部变量或者理解为私有属性,不能通过对象名的方式进行访问,可以使用闭包函数访问
	var ff=function(){
    
    
		return bb;
	}
	return ff;
}

class keyword

ES6 introduces the class keyword which can be used to define classes, but browser support needs to be considered

class Person{
    
    
	constructor(){
    
     //定义构造器函数,只能定义一个,名称固定,参数个数没有限制。如果需要定义多个构造器可以考虑使用arguments判断参数格式
		if(arguments.length>1){
    
    
			this.username=arguments[0];// this用于定义公共属性
			this.age=arguments[1];
		} else if(arguments.length==1){
    
    
			this.username=arguments[0];
			this.age=99;
		} else {
    
    
			this.username="zhangsan";
			this.age=18;
		}
	}
	//可以定义成员方法,规则是【方法名称(参数列表){}】
	show(){
    
    
		return "Hello "+this.username+",今年"+this.age+"岁了!";
	}
}

var p=new Person();
document.writeln(p.show());

p=new Person("lisi",55,true); //按照处理逻辑并没有接收arguments[2],所以true没有使用
document.writeln(p.show());

3 ways to call functions indirectly

Call p.pp(1,2,3) directly;

The call method dynamically calls the function

var ee=function(arr,fn){
    
     //其中参数fn就是调用时才设置的函数
	for(var index in arr){
    
    
		fn.call(null,index,arr[index]); //调用函数fn,参数1调用的函数所属于的对象,如果值为null则表示window,后面参数则是调用函数时的参数
	}
}

//调用ee函数
ee([2,3,4,5,6],function(index,ele){
    
     //function()就是传递给fn的函数
	document.writeln("第"+index+"个元素是"+ele+"<br/>");
});

apply dynamically calls the function

When calling a function through call, each parameter must be listed in parentheses in detail, but when calling a function dynamically through apply, you can use arguments to represent all parameters in parentheses

var ff=function(a,b){
    
    
alert(a+b);
}
ff.call(window,12,23); //12和23对应的就是函数中的参数,通过call方法动态调用时需要为每
个调用方法逐个的传入参数,写法为12,23
ff.apply(window,[12,23,34,56]);//通过apply方法动态调用方法时,能与arguments一次性传
入多个参数,例如这里的参数就是一个数组[12,23,34,56]

Function parameter handling

JavaScript adopts the value passing method. When a function is called through an actual parameter, what is passed into the function is not the actual parameter itself, but the value of the actual parameter, because modifying the parameter value in the function will not have any impact on the actual parameter. Composite type parameter is a reference

<meta charset="UTF-8">
<script>
function ff(person) {
    
    
if (typeof (person) == 'object') {
    
    
person.age = 100;
} else alert('参数类型不是复合类型' + typeof person);
}
person={
    
    "age":99,toString:function(){
    
    return "age:"+this.age}};
ff(person);
document.writeln(person);
</script>

new problem with parameters

There is no concept of function overloading in JavaScript. The function name is the unique identifier of the function. If two functions with the same name are defined, the

function ff(person){
    
    
if(typeof(person)=='object'){
    
    
person.age=100;
} else
alert('参数类型不是复合类型'+typeof person);
}
ff(); //person形参对应的实参为undefined

prototype

JavaScript is a prototype-based language. Prototypes can be understood as originals, and objects can be created by replicating the originals exactly. JavaScript objects have a public property called prototype, which is the prototype object prototype of the constructor.

function Person(){
    
    
	this.name="Nicholas";
	this.age=29;
	this.job="Software Engineer";
	this.sayName=function(){
    
    }
}

Guess you like

Origin blog.csdn.net/qq_39756007/article/details/127865484