登录
原创

JavaScript函数

发布于 2021-04-09 阅读 544
  • JavaScript
原创

一、声明函数的方式(3种)

方式一:

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

方式二:

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

方式三:

var sum = new Function('num1', 'num2', 'return num1 + num2');
alert(sum(8, 8));

第三种方式不推荐,因为这种语法会导致解析两次代码(第一次解析常规ECMAScript代码,第二次是解析传入构造函数中的字符串),从而影响性能。但我们可以通过这种语法来理解“函数是对象,函数名是指针”的概念。

二、函数传递函数

2.1 函数返回值作为参数进行传递

function test(sum, num) {
	return sum + num;
}

function sum(num) {
	return num + 10;
}

var result = test(sum(10), 10);
alert(result);

2.2 函数本身作为参数进行传递

function test(sum, num) {
	return sum(num);
}

function sum(num) {
	return num + 10;
}

var result = test(sum, 10);
alert(result);

三、apply()和call()方法

apply()、call()方法可以调用方法,
优点:可以扩充作用域、减少代码间的耦合性

apply()使用方法:

要调用的方法名.apply(作用对象, [参数1, 参数2, 、、、])

也可以这样写,简化多参数传递的书写:

要调用的方法名.apply(作用对象, arguments)
使用示例:

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

function test2(num1, num2) {
	return test1.apply(this, [num1, num2]);
}
alert(test2(10, 10));

function test1(num1, num2) {
	return num1 + num2;
}
function test2(num1, num2) {
	return test1.apply(this, arguments);
}
alert(test2(10, 12));

call()使用方法:

要调用的方法名.call(作用对象, 参数1, 参数2, 、、、)

使用示例:

unction test1(num1, num2) {
	return num1 + num2;
}
function test2(num1, num2) {
	return test1.call(this, num1, num2);		//call和apply的区别就在参数的传递上,其他地方一样
}
alert(test2(10, 10));

例如在全局和局部有相同的变量名称,调用不同位置的变量可以这样:

var color = '蓝色';

var box = {
	color: '红色'
};

function getColor() {
	alert(this.color);
}

getColor();
getColor.call(window);
getColor.call(this);
getColor.call(box);

结果依次弹出:
call1.png
call2.png
call3.png
call4.png

根据call()中填写的作用对象,方法getColor中的 this.color 中的this 指向不同的作用对象
方法getColor()本身是处于window对象中,所以直接执行是它里面的this也是指向window对象,this.color指向window下的color属性—即 ‘var color = ‘蓝色’;’ 处的 ‘蓝色’
‘getColor.call(window);
getColor.call(this);’这两句也是指向window对象,所以同上
‘getColor.call(box);’中指明对象为box,所以getColor()方法中的 this.color 指向 box 中的color—即‘color: ‘红色’’

评论区

零00
7粉丝

时光荏苒,我自清欢

0

0

0

举报