You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何'this'值为undefined?对象方法赋值变量后调用输出异常解析

为什么这段代码会输出 "Hello, undefined"?

咱们一步一步拆解你的代码,就能搞清楚this为啥变成undefined了:

先看你的代码:

var person = { 
  name: "John", 
  message: function () { 
    console.log("Hello, " + this.name) 
  } 
} 
var messageFunc = person.message 
messageFunc(); // 输出 "Hello, undefined"

关键:this的绑定是调用时决定的

JavaScript里的this从来不是在函数定义的时候固定的,它完全取决于你怎么调用这个函数:

  • 当你写person.message()的时候,函数是作为person对象的方法被调用的,这时候this就会绑定到person对象上,所以this.name就是person.name,输出"Hello, John"。
  • 但你把person.message赋值给messageFunc之后,事情就变了:messageFunc现在只是一个独立的函数引用,和person对象没有绑定关系了。当你直接调用messageFunc()的时候,函数是在全局上下文(非严格模式)或者作为独立函数(严格模式)被调用的:
    • 在非严格模式下,这种直接调用的函数里的this会指向全局对象(浏览器里是window,Node.js里是global),而全局对象里没有定义name属性,所以this.name就是undefined。
    • 如果是在严格模式下,直接调用的函数里的this会直接是undefined,这时候访问this.name会直接抛出Cannot read properties of undefined的错误——不过你的代码输出了undefined,说明是在非严格模式下运行的。

怎么修复这个问题?

如果想让messageFunc调用时依然指向person,可以用这几种方式:

  • 使用bind()绑定上下文:
    var messageFunc = person.message.bind(person);
    messageFunc(); // 输出 "Hello, John"
    
  • 调用时用call()或apply()指定上下文:
    messageFunc.call(person); // 输出 "Hello, John"
    
  • 用箭头函数(ES6+),箭头函数的this会继承定义时的上下文:
    var person = { 
      name: "John", 
      message: function () { 
        const innerFunc = () => console.log("Hello, " + this.name);
        return innerFunc;
      } 
    }
    var messageFunc = person.message();
    messageFunc(); // 输出 "Hello, John"
    

内容的提问来源于stack exchange,提问作者Büşra Şirin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:36:21