/**
* 函数的this理解
* 经常看到的一句话:就是js代码在执行时,谁调用这个函数或方法,this关键字就指向谁
* 为什么说是js代码在执行时?
* 因为js设计的就是代码在浏览器中运行时才为this分配上下文,这是它的坑
* 也就是说this的指向只有在代码运行时才确定的,而不是定义时确定的
* 谁调用这个函数或方法,this关键字就指向谁,才决定了this的作用域!
* 所以js中的this指向谁,是由下边的这几种调用模式决定的
* js中的调用模式
* 普通函数调用
作为方法来调用
作为构造函数来调用
使用apply/call方法来调用
Function.prototype.bind方法
es6箭头函数
*/
console.log('**普通函数调用========this指向 window');
function sum() {
console.log(this);
}
sum();
console.log('**作为方法来调用======this 指向当前对象');
var peroson = {
name: 'lisi',
age: 15,
say() {
console.log(this);
return this.name + this.age;
}
};
peroson.say();
console.log('**作为构造函数来调用======this 指向当前实例化的对象');
function Animal(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(this);
return this.name + ' ' + this.age;
};
}
let animal = new Animal('哈士奇', 5);
console.log(animal.run());
console.log(
'**使用apply/call方法来调用======this指向取决于两个方法的第一个参数'
);
function Rectangle(width, height) {
this.width = width;
this.height = height;
this.getRectangle = function() {
console.log(this);
return `长度是:${width},高度是:${height}`;
};
}
let a = new Rectangle(10, 20);
a.getRectangle();
let model = {
width: 35,
height: 50
};
a.getRectangle.apply(model);
let arr = [1, 5, 25, 68, 59];
console.log(Math.max.apply(null, arr));
console.log(Math.max.apply(undefined, arr));
console.log('**Function.prototype.bind方法===== this指向当前的这个对象函数');
function Fruit(name, color) {
this.name = name;
this.color = color;
this.change = function() {
console.log(this);
setTimeout(function() {
console.log(this);
console.log(this.name + '的颜色是 ' + this.color);
}, 1000);
};
}
let apple = new Fruit('苹果', '黑色');
apple.change();
function Fruit(name, color) {
this.name = name;
this.color = color;
this.change = function() {
console.log(this);
setTimeout(
function() {
console.log(this);
console.log(this.name + '的颜色是' + this.color);
}.bind(this),
1000
);
};
}
console.log(
'**es6的箭头函数===== es6里面this指向固定化,始终指向父级的运行上下文环境,因为箭头函数没有this,因此它自身不能进行new实例化,同时也不能使用call, apply, bind等方法来改变this的指向'
);
function Fruit(name, color) {
this.name = name;
this.color = color;
this.change = function() {
console.log(this);
setTimeout(() => {
console.log(this);
console.log(this.name + '的颜色是' + this.color);
}, 1000);
};
}
