1. 方法调用
<script>
var age = 38;
var obj = {
age: 18,
getAge: function () {
console.log(this.age);
}
};
// this指向了谁? 指向了obj
obj.getAge();
var fn = obj.getAge;
// this指向了谁 指向widow
fn();
</script>
2.函数调用
<script>
var age = 38;
var obj = {
age: 18,
getAge: function () {
var fn = function () {
console.log(this.age);
};
// this指向了谁
console.log(this);
fn();
}
};
obj.getAge();
</script>
3.构造函数
<script>
function MadeCat(name,age) {
// this指向了谁? //Madecat
console.log(this);
this.name = name;
this.age = age;
}
var cat = new MadeCat('小白',2);
</script>
4. call apply bind
<script>
// 1. 声明两个变量和一个函数
var username = '张三';
var age = 18;
function say(provice, city) {
console.log('this=', this);
console.log(`我来自${provice}${city}`);
console.log(`我叫${this.username},今年${this.age}岁`);
}
// 2. 创建一个对象
var person = {
username: 'laohu',
age: 23
};
var persons = {
username: 'xb',
age: 23
};
say('广东', '深圳');
/**
* 使用call改变this的指向
* @param person this要指向的对象
* @param '广西','贵港' 实参,可以传多个
*/
say.call(person, '广西', '贵港');
/**
* 使用apply改变this的指向
* @param person this要指向的对象
* @param ['广西','贵港'] 实参,是个数组,所有参数都放入数组内
*/
say.apply(persons, ['hn', 'xy']);
</script>
<script>
// 1. 声明两个变量和一个函数
var username = '张三';
var age = 18;
function say(provice, city) {
console.log('this=', this);
console.log(`我来自${provice}${city}`);
console.log(`我叫${this.username},今年${this.age}岁`);
}
// 2. 创建一个对象
var person = {
username: '老胡',
age: 100
};
say('广东', '深圳');
/**
* 3.使用bind改变this的指向
* - 使用bind后会获得一个新的函数,新的函数具备跟原函数一样的功能
* - 新函数的this指向发生了改变
*/
var say2 = say.bind(person);
// 调用新函数,跟原函数一模一样,不过this发生了改变
say2('广西', '贵港');
</script>