MST

星途 面试题库

面试题:JavaScript 中函数 this 绑定规则基础应用

请分析以下代码中函数 `func` 执行时 `this` 的指向,并解释原因。 ```javascript const obj = { value: 1, func: function() { return this.value; } }; const func = obj.func; console.log(func()); ```
36.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. this 的指向this 指向全局对象(在浏览器环境中是 window,在 Node.js 环境中是 global)。
  2. 原因
    • const func = obj.func; 这行代码执行时,func 是从 obj 对象上提取出来的函数。
    • 然后调用 func(),这种调用方式是普通函数调用。在普通函数调用中,this 指向全局对象(严格模式下 thisundefined)。因为此时函数 func 不再是作为 obj 对象的方法调用,而是作为独立函数调用,所以 this 不会指向 obj