闲来无事,写写文章----JS面试题
js中call,apply,bind如何使用,使用场景
一句话,
改变this指向
下面举几个简单的例子大家就知道了
<script>
let obj1 = {
name: "flx",
sex: '男',
user: function (args) {
console.log("姓名:", this.name);
console.log("性别:", this.age);
console.log("年龄", args);
}
}
let obj2 = {
name: "cxy",
sex: '女',
user: function () {
console.log("姓名:", this.name);
console.log("性别:", this.age);
console.log("年龄", args);
}
}
// 正常的调用
obj1.user(26);
// 姓名:flx 性别:男 年龄:26
obj2.user(24);
// 姓名:cxy 性别:女 年龄:24
// 使用call改变this指向
obj1.user.call(obj2, 124);
// 姓名:cxy 性别:女 年龄:124
obj2.user.call(obj1, 126);
// 姓名:flx 性别:男 年龄:126
</script>
var name = 'cxy', age = 24
var obj = {name: 'flx', age: 26}
function myFun(a,b) {
console.log(this.age)
console.log(this.name)
}
// this 指向 window
myFun()
// 24
// cxy
// 改变this指向
// this指向了obj
myFun.call(obj)
// 26
// flx