1.为什么要用this
var car = {
type: 'truck',
size: 'big',
describe: function() {
// console.log(`The car is ${car.type}, the size is ${car.size}.`);
console.log(`The car is ${this.type}, the size is ${this.size}.`);
}
}
car.describe();
一定程度上减少代码量,提高代码整洁性和可读性
2.this绑定方式
默认绑定
function learning() {
console.log(this);
}
learning();
函数被调用,this默认指向全局Window对象
隐式绑定
var student = {
name: '张三',
age: 20,
sex: '男',
introduce: function() {
console.log(`姓名:${this.name}`);
console.log(`年龄:${this.age}`);
console.log(`性别:${this.sex}`);
}
}
student.introduce()
对象方法被调用时发生隐式绑定,this指向调用该方法的对象
硬绑定
var animal = {
name: '动物',
sayName: function() {
console.log(`这个是${this.name}`);
}
}
var dog = {
name: '毛球',
}
var cat = {
name: '奥利奥',
}
animal.sayName.call(dog);
animal.sayName.apply(cat);
通过call、apply改变this指向
构造函数绑定
function Person(name) {
this.name = name;
this.sayName = function() {
console.log(`他的名字叫${this.name}`);
}
}
var name = '小白';
var person = new Person('小红');
person.sayName();
创建构造函数,对象实例化,this与实例化后的对象进行绑定
3.练习
function a() {
function b() {
console.log(this);
function c() {
"use strict";
console.log(this);
}
c();
}
b();
}
a();
严格模式下this为undefined
var name = '小白';
function special() {
console.log('姓名' + this.name);
}
var girl = {
name: '小红',
detail: function() {
console.log('姓名' + this.name);
},
woman: {
name: '小黄',
detail: function() {
console.log('姓名' + this.name);
}
},
special: special,
}
girl.detail();
girl.woman.detail();
girl.special();
special函数放入girl中,girl调用special方法,this隐式绑定到girl上
4.总结
不管函数声明的位置,this始终动态指向实际调用函数的对象