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

JavaScript中如何从子对象函数访问父构造函数对象的变量

解决JavaScript嵌套对象函数访问父对象变量的问题

咱们先揪出问题根源:你写的this.this.foo是完全错误的逻辑——当调用test.bar.bite()时,函数内部的this指向的是bar这个子对象,而非外层的myObject实例,自然拿不到foo变量。下面给你几个精简的实现方案,按需选用:

方案1:闭包保存外层this(兼容全环境)

在构造函数里先把外层实例的this存成一个变量,嵌套函数就能通过闭包访问到它,这是兼容性最好的写法:

var myObject = function(){ 
  var self = this; // 把父对象的this存起来
  this.foo = 'stuff';
  this.bar = { 
    bit: 'things', 
    bite: function(){ 
      return self.foo; // 直接用保存的self访问父对象的foo
    } 
  };
}
var test = new myObject();
test.foo = 'blarg';
test.bar.bite(); // 返回'blarg'

方案2:ES6箭头函数(最精简)

箭头函数不会绑定自己的this,会直接继承外层作用域的this,代码能省掉额外变量,写法最清爽:

var myObject = function(){ 
  this.foo = 'stuff';
  this.bar = { 
    bit: 'things', 
    bite: () => this.foo // 这里的this就是父对象实例的this
  };
}
var test = new myObject();
test.foo = 'blarg';
test.bar.bite(); // 返回'blarg'

如果你的项目环境支持ES6+,这个方案优先选。

方案3:手动绑定this(逻辑直观)

直接给bite函数绑定父对象的this,明确指定函数执行时的this指向:

var myObject = function(){ 
  this.foo = 'stuff';
  this.bar = { 
    bit: 'things', 
    bite: function(){ 
      return this.foo;
    }.bind(this) // 把函数的this绑定到父对象实例
  };
}
var test = new myObject();
test.foo = 'blarg';
test.bar.bite(); // 返回'blarg'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:15:44