一、call&apply与bind区别
call和apply方法对函数直接调用
bind方法后面还需要()来进行调用才可以
<!DOCTYPE html>
<html lang="cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>测试页面</title>
</head>
<body>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
var zs = {
name: '张三',
age: 24,
say: function () {
console.log(`姓名: ${this.name}, 年龄: ${this.age}`)
}
}
var ls = {
name: '李四',
age: 18
}
zs.say()
zs.say.apply(ls)
zs.say.call(ls)
zs.say.bind(ls)()
</script>
</body>
</html>
输出结果.png
二、call与apply区别
call 传参参数一一对应
apply 第二个参数是一个数组
bind 有两种书写方式
<!DOCTYPE html>
<html lang="cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>测试页面</title>
</head>
<body>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
var zs = {
name: '张三',
age: 24,
say: function (gender, city) {
console.log(`姓名: ${this.name}, 年龄: ${this.age}, 性别: ${gender}, 城市: ${city}`)
}
}
var ls = {
name: '李四',
age: 18
}
zs.say('男', '上海')
zs.say.call(ls, '女', '北京')
zs.say.apply(ls, ['女', '北京'])
zs.say.bind(ls)('女', '北京')
zs.say.bind(ls, '女', '北京')()
</script>
</body>
</html>
输出结果2.png
网友评论