<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//这三个函数都可以改变函数内部this的指向
//函数.call(希望this指向的对象,参数1, 参数2…); 调用之后,会直接执行函数
//函数.apply(希望this指向的对象,[参数1, 参数2…]); 调用之后,会直接执行函数
//函数.bind(希望this指向的对象,参数1, 参数2…); 调用之后,不会执行函数。
/******** call ********/
var age = 40;
function common(x , y){
//console.log(this);
console.log(this.age + x + y);
}
var o1 = {
age:20
};
var o2 = {
age:30
};
common.call(o1, 2, 3); // 结果:25 ,改变了common内部this的指向为o1,所以this.age的值是20
common.call(o2, 2, 3); // 结果:35,改变了common内部this的指向为o2,所以this.age的值是30
/************ bind ************/
function B(x, y){
console.log(this, x + y); // this 表示 window对象
}
B.call(new Object(), 3, 4); //结果:{} 7
B.apply(new String(), [3, 4]); //结果:String {"", length: 0} 7
B.bind(new Object(), 3, 4); //结果:无,直接这些写,B函数是不会执行的,如果希望它执行,那么在加小括号
B.bind(new Object(), 3, 4)(); //结果:{} 7,改变B中的this指向后,并执行B函数
B.bind(new Object())(3, 4); //结果:{} 7,改变B中this指向的时候不传递其他参数,当函数调用的时候,在传递x和y的值
/********* apply查找数组中的最大值 **********/
var arr = [3, 4, 2, 6, 7, 10 ,8 ,1];
console.log(Math.max.apply(null, arr)); //结果:10
console.log(Math.min.apply(null, arr)); //结果:1
/*function Math(){
this.max = function (x, y, z) {
return 最大值;
}
}
var m = new Math();
m.max.apply(null, arr);*/
</script>
</body>
</html>