webveuje/js/demo/callapply.html
2021-03-23 10:58:10 +08:00

71 lines
1.8 KiB
HTML
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// call,apply 用其他函数的方法
function add(a,b){
return a+b;
}
function sub(a,b){
return a-b;
}
var a1 = add.apply(sub,[4,2]);  //sub调用add的方法
var a2 = sub.apply(add,[4,2]);
// alert(a1); //6
// alert(a2); //2
/*call的用法*/
var a1 = add.call(sub,4,2); //sub调用add的方法
console.log(a1)
// 实现继承 cat 继承animal
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
function Cat(name){
console.log(this)
Animal.apply(this,[name]); // this new以后指向的是他的实例cat 但是cat的构造函数里面通过apply把当前的this指向了animal
//所以他实例出来的对象cat 就能用 animal里面的属性和方法
}
var cat = new Cat("咕咕");
cat.showName();
/*call的用法*/
Animal.call(this,name);
// bind
var a = {
b : function(){
var func = function(){
console.log(this.c);
}
func.bind(this)(); //等价于 this.func()
},
c : 'Hello!'
}
a.b();
//Hello!
</script>
</head>
<body>
<p> call和apply的作用都是 修改this的指向</p>
<p> call和apply 操作的都是函数 而不是对象</p>
<p>区别:
<p>call 需要的参数都写上(单独的)</p>
<p>apply 需要的参数 如果有多个的话,需要用数组的形式传过去</p>
</p>
<p>bind()方法主要就是将函数绑定到
<p>f.bind(obj)实际上可以理解为obj.f()</p>
</p>
</body>
</html>