<!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>
</head>
<body>
<script>
var o = {
sayHi: function(){
console.log('我是改变后this指向');
}
}
function fn(a,b){
console.log(this);
console.log(a+b);
}
fn.call(o,1,3);
// call第一个可以调用函数,第二个可以改变函数内的this指向
// call的只要作用可以实现继承
function Father(uanme,age,sex){
this.uanme = uanme;
this.age = age;
this.sex = sex;
}
function Son(uname,age,sex){
Father.call(this,uname,age,sex);
}
var son = new Son('ann',18,'nv');
console.log(son);
</script>
</body>
</html>
<!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>
</head>
<body>
<script>
var o = {
uname: 'andy'
};
function fn(arr){
console.log(this);
console.log(arr);
}
fn.apply(o,['blue','pink']);
// 1.也是调用函数 第二个可以改变函数内部的this指向
// 2.但是他的参数必须是数组(伪数组)
// 3.apply的主要应用
var arr = [1,3,35,4,64,34,35]
var max = Math.max.apply(Math,arr)
console.log(max);
</script>
</body>
</html>
<!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>
</head>
<body>
<button>点击</button>
<button>点击</button>
<button>点击</button>
<script>
var o = {
name: 'andy'
};
function fn(a,b){
console.log(this);
console.log(a,b);
}
var f = fn.bind(o);
f(1,2);
// 不会调用原来的函数 可以改变原来函数内部的this指向
// 2.返回的是原函数改变this之后产生的新函数
// 3.如果有的函数我们不需要立即调用,但是又想改变和这个函数内部的this指向此时用bind
// 4.当我们有一个按钮,当我们点击之后,就禁用这个按钮,3秒之后开启这个按钮
// var btn = document.querySelector('button');
// btn.onclick = function(){
// this.disabled = true;
// // var that = this
// setTimeout(function(){
// this.disabled = false;
// }.bind(this),3000) //bind里面的this是在定时器函数外面 所以还是指的btn
// }
var btns = document.querySelectorAll('button');
for(var i = 0;i<btns.length;i++){
btns[i].onclick = function(){
this.disabled = true;
setTimeout(function(){
this.disabled = false
}.bind(this),2000)
}
}
</script>
</body>
</html>