this详解

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值