this详解
关于this指向的核心,记住最核心的一句话: 哪个对象调用函数,函数里面的this指向哪个对象。
1. 全局使用
console.log(this);
//此时指向 window对象
var a = "12";
//相当于 window.a = "12"
console.log(this.a); //输出12
2. 普通函数调用
function a(){
alert(this.name);
}
a();
// 此时 this指向windows对象 因为默认是 window.a()调用 弹出内容为空
function b(){
alert(this.name);
}
var name = "12";
//此时this 一样指向 windows对象, 弹出是 12 name会经过变量申明提升到顶部
3. 构造函数调用
function Person(){
this.age = 12;
this.name = "12";
}
var person = new Person();
//此时 此时this 指向person实例
4. 对象函数的调用
var person = {
firstName: 'Tom',
lastName: 'Grey',
name : function (){
return this.firstName + "-" + this.lastName;
}
}
console.log(person.name());
//输出Tom-Grey
//person调用 指向person
5. apply和call调用
例子1
var a = {name : '张三'};
var b = {
name: "李四",
sayName: function (){
alert(this.name);
}
};
b.sayName.call(a);
//弹出张三
//call 作用 第一 改变作用域对象 本来this 指向b 使用 call改变作用域对象 this指向 a, 第二借用b的方法调用
例子2
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
//该例子来源于火狐开发者MDN
/*
此时执行 Product.call(this, name, price);相当于 给Food添加name price属性
*/
console.log(JSON.stringify(new Food("cheese", 5)));
//结果 "{"name":"cheese","price":5,"category":"food"}"
call 与apply的区别在于接收参数,call参数是接收参数列表 apply接收的是参数数组
不展开对 call 和 apply的应用
参考: https://blog.csdn.net/weixin_37722222/article/details/81625826