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

JavaScript函数this指向问题:为何返回结果非预期{s:3}?

问题原因及解决办法

你预期返回{s:3}但没得到,核心问题是普通函数的this指向由调用方式决定,不是定义位置。

你代码里sec返回的那个匿名函数,是通过t()直接调用的——这种无对象绑定的普通函数调用,非严格模式下this会指向全局对象(浏览器是window,Node.js是global),严格模式下是undefined。所以this.s = '3'其实是给全局对象加了属性,返回的自然是全局对象,不是你想要的新对象。

几种解决方式:

  1. 直接返回新对象
    不用依赖this,在嵌套函数里直接创建并返回目标对象:

    const obj = {
        name:  'Hi',
        first: () => {
            return this
        },
        other: {
            name: 'last',
            sec: function() {
                this.c = '2'
                return function() {
                    return { s: '3' }; // 直接返回新对象
                }
            }
        }
    }
    
    const t = obj.other.sec()
    console.log(t()) // 输出 {s:3}
    
  2. 用箭头函数+外部变量
    先定义一个空对象,用箭头函数捕获这个变量(箭头函数不绑定自己的this,会继承外层作用域):

    const obj = {
        name:  'Hi',
        first: () => {
            return this
        },
        other: {
            name: 'last',
            sec: function() {
                this.c = '2'
                const target = {};
                return () => {
                    target.s = '3'
                    return target;
                }
            }
        }
    }
    
    const t = obj.other.sec()
    console.log(t()) // 输出 {s:3}
    
  3. 用bind绑定this
    提前创建目标对象,把嵌套函数的this绑定到这个对象上:

    const obj = {
        name:  'Hi',
        first: () => {
            return this
        },
        other: {
            name: 'last',
            sec: function() {
                this.c = '2'
                const target = {};
                return function() {
                    this.s = '3'
                    return this;
                }.bind(target);
            }
        }
    }
    
    const t = obj.other.sec()
    console.log(t()) // 输出 {s:3}
    

内容的提问来源于stack exchange,提问作者Asking

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:20:27