js 中的this指针

this 指针

含义

-this 代表当前正在执行某个方法的对象,this 总是指向调用该方法的对象。

this 的指向模式

  1. 函数调用,在一个单纯的函数里面,this 的指向 window,因为是 window 调用的函数补: 构造函数 new 下调用,this 指向被构造的新对象 / appl,call bind 的调用,this 指向第一个参数
  2. 对象里的方法调用,this 总是指向调用他所在方法的对象,this 的指向与所在方法的调用位置有关,与方法的声明位置无关;

函数调用

一般函数调用

当函数被单独调用时,this 指向的是 全局对象;

// 在全局函数里声明一个 x
let x = "2";

// 此时的this 指向的是window对象
// 因为是全局调用的函数
let fn = function () {
  console.log(this.x);
};

// 显示结果
fun(); // 2

构造函数 new

  • 以构造函数形式调用时候,此时 this 代表创建的对象
// 声明一个函数
function Person(name) {
  this.name = name;
  console.log(this);
}

// 仅仅输出该函数,结果是window
console.log(Person("张")); // window

//使用构造函数
var p1 = new Person("jack"); // Person {name: 'jack'}
var p2 = new Person("lucy"); // Person {name: 'lucy'}

bind() call() apply()

bind()

  • 格式:f.bind(someObject)
  • 定义:会创建一个和 f 一样的函数,并将 this 永久的绑定给了 bind 的第一个参数,
  • 注意:bind 只能生效一次,即被 bind 创建的函数,不能被 bind 拿来使用
function f() {
  return this.a;
}

let g = f.bind({ a: "张" });
console.log(g()); // 张

// 因为 g是有bind 构成的,所以无法改变
let h = g.bind({ a: "zzz" });
console.log(h()); //张

call()和 apply()

  • 格式:call(thisObj,Object) apply(thisObj,[argArry])

  • 定义:调用一个对象的一个方法,以另一个对象替换当前对象

// 命名全局变量
let name = "钊";

let demo = {
  name: "张",
  getName: function () {
    console.log(this.name);
  },
};

let demo2 = {
  name: ["zzz", "卓"],
};

demo.getName.call(demo); //张
demo.getName.apply(demo2); //Array(2) ['zzz', '卓']

补充

  • 当 bind(), call()和 apply()传入 null 或 undefined 时, 会自动将 this 绑定到全局对象
function foo() {
  console.log(this);
}
let bar = foo.bind(null);

foo.call(null); //window
foo.apply(undefined); // window
bar(); // window

对象的方法调用

  • 当函数作为对象里的方法被调用时,this 被设置为调用该函数的对象

  • 1.先定义函数,再将其附属到对象中

//声明函数
let fn = function () {
  console.log(this.x);
};

let x = "2";

// 放入位置
let obj = {
  x: "1",
  fn: fn,
};

obj.fn(); // 1
fn(); // 2
  • 2.将函数作为对象里的方法调用
let o = {
  php: 22,
  f: function () {
    return this.php;
  },
};

console.log(o.f()); //22

优先级规则

  • call、apply 和 new 都可以调用函数,无法同时使用

  • new > call、apply 和 bind > 对象方法引用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值