【问题标题】:Unable to access internal object after instantiation实例化后无法访问内部对象
【发布时间】:2023-02-06 08:51:52
【问题描述】:

我有一个非常简单的带有实例化对象的代码,我通过原型公开了一些方法。这是代码:

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: 'dfvdfvd'
    };
  }

  function get() {
    return this._obj[1];
  }

  MyClass.prototype.take = () => {
    get.call(this);
  }

  return MyClass;
}());

let x = new MyClass();
console.log(x.take())

但我一直收到_obj作为undefined。我在这里错过了什么?

【问题讨论】:

  • this 不是您所指的。

标签: javascript


【解决方案1】:

问题是MyClass.prototype.take 是一个箭头函数,但对于所有箭头函数,this 都是undefined(参见MDN)。只需将其设为常规功能即可。

另外,确保从MyClass.prototype.take() 返回一个值,否则你将得到undefined。

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: 'dfvdfvd'
    };
  }

  function get() {
    return this._obj[1];
  }

  MyClass.prototype.take = function() {
    return get.call(this);
  }

  return MyClass;
}());

let x = new MyClass();
console.log(x.take())

【讨论】:

  • 哇...我自己也不会想到...压力太大以至于我什至忘记了 return 关键字...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 2016-08-07
  • 2011-01-03
  • 2016-01-18
  • 2018-10-04
相关资源
最近更新 更多