javascript高级程序设计阅读收获(10.10)——函数属性与方法

本文探讨了JavaScript中函数的length属性,展示了如何通过apply和call方法改变函数调用的上下文并传递参数,同时也解释了bind方法在创建新函数时绑定this值的作用。通过对这些特性的理解,可以更好地掌握JavaScript的函数操作。
摘要由CSDN通过智能技术生成

1.length属性

function aaa(a1){
	
}
function bbb(a1,a2){

}
function ccc(a1,a2,a3){
	
}
console.log(aaa.length);//1
console.log(bbb.length);//2
console.log(ccc.length);//3
  1. length属性保存函数定义的命名参数的个数。

2.apply和call方法

function sum(num1,num2){
	console.log(num1 + num2);
}
sum.apply(this,[10,20]);//30

function aaa(num1,num2){
	return sum.apply(this,arguments);
}
aaa(20,20);//40
  1. apply方法,第一个参数为函数绑定this值,第二个参数是一个数组或则arguments对象,用来传参。
function sum(num1,num2){
	return num1 + num2;
}
function callSum(num1,num2){
	return sum(this,num1,num2);
}
console.log(callSum(30,20));//30
  1. call方法,与apply方法相同,但是他的传参必须将参数一个一个的列出来。
window.color='red';
let o ={
	color:'blue',
};
function sayColor(){
	console.log(this.color);
}
sayColor.call(this);//red
sayColor.call(window);//red
sayColor.call(o);//blue
  1. apply和call真正强大的地方在于控制函数调用上下文即函数体内this值的能力

3.bind方法

window.color = 'red';
var o = {
	color:'blue'
}
function sayColor(){
	console.log(this.color);
}
let objectSayColor = sayColor.bind(o);
objectSayColor();//blue
  1. bind方法返回一个以参数值为的this新函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子 旭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值