Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Javascript - this

Back


this


Explicit Function Binding

//call()
const person1 = {
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};

const person2 = {
  firstName: "John",
  lastName: "Doe",
};

let x = person1.fullName.call(person2);

console.log(x); //John Doe
//解析: person1的fullname定义了匿名函数
//调用时, 使用call()将person2传递给this

//bind(): this keyword set to the provided value
const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};

const member = {
  firstName: "Hege",
  lastName: "Nilsen",
};

let fullName = person.fullName.bind(member);
//解析: fullName是匿名函数,不是object的方法,所以this不是指代object
//使用bind()将this指代为参数, 即member
//bind()的用处, 当object是异步时, 直接使用this指代object本身会发生返回undefined的情况. 此时使用object.property.bind(object), 因为object是参数,所以会等待到object完全加载时, 才传入到this, 以此解决异步返回undefined的情况.

TOP