关于"this"面试题

262 阅读1分钟

题目1

const object = {
  message: "Hello, World!",

  getMessage() {
    const message = "Hello, Earth!";
    return this.message;
  }
};

/* 
  this 指向 object
  this.message => object.message => Hello, World!
*/
console.log(object.getMessage()); // Hello, World!

题目2

var name = "Jack";
function Pet(name) {
  this.name = name;

  /* 
    箭头函数中的this在定义的时候就已经决定了,与声明所在的上下文相同
    此处的this指向Pet,所以this.name一直会输出 Fluffy
  */
  this.getName = () => this.name;
}

const cat = new Pet("Fluffy");
console.log(cat.getName()); // Fluffy

const { getName } = cat;
console.log(getName()); // Fluffy

题目3

var name = "Jack";
function Pet(name) {
  this.name = name;

  // this.getName = () => this.name;
  this.getName = function () {
    return this.name;
  };
}

const cat = new Pet("Fluffy");
console.log(cat.getName()); // this指向Pet,this.name => Pet.name => Fluffy

const { getName } = cat;
console.log(getName()); // this指向Window,this.name => Window.name => Jack

题目4

const object = {
  message: "Hello, World!",
  logMessage() {
    console.log(this.message); // this指向Window,this.message => Window.message => undefined
  }
};

/* 
  setTimeout/setInterval 这些函数中传递的函数中的this指向,在非严格模式下指向的是全局对象
*/
setTimeout(object.logMessage, 1000);

题目5

const object = {
  who: "World",
  greet() {
    return `Hello, ${this.who}!`;
  },
  farewell: () => {
    return `Goodbye, ${this.who}!`;
  }
};

console.log(object.greet()); // this指向object => this.who => object.who => World
console.log(object.farewell()); // this指向Window => this.who => Window.who => undefined

题目6

var length = 4;
function callback() {
  console.log(this.length); // this指向Window => this.length => Window.length => 4
}

const object = {
  length: 5,
  method(callback) {
    callback();
  }
};

object.method(callback, 1, 2);

题目7

var length = 4;
function callback() {
  console.log(this);
  console.log(this.length); // this指向Arguments => this.length => Arguments.length => 3
}

const object = {
  length: 5,
  method() {
    arguments[0]();
    /* 
      arguments[0]() => 可以看做为 arguments.0.call(arguments)
    */
  }
};

object.method(callback, 1, 2);