无法在实例化后访问内部对象

huangapple go评论64阅读模式
英文:

Unable to access internal object after instantiation

问题

我有一个非常简单的代码,其中有已实例化的对象,我通过原型暴露了一些方法。以下是代码:

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())

但是,我一直得到 _objundefined。我在这里漏掉了什么?

英文:

I have a very simple code with instantiated objects and I'm exposing some methods via a prototype. Here's the code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: &#39;dfvdfvd&#39;
    };
  }

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

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

  return MyClass;
}());

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

<!-- end snippet -->

but I keep getting _obj as undefined. what am I missing here?

答案1

得分: 1

问题在于MyClass.prototype.take是一个箭头函数,但箭头函数没有它们自己的this(参见MDN),因此this是默认的window,而this._objundefined。你可以要么手动绑定它,要么像下面我所做的那样将其变成常规函数。

另外,请确保从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())

希望这对你有帮助。

英文:

The issue is that MyClass.prototype.take is an arrow function, but arrow functions don't have their own this (see MDN), thus this is the default window and this._obj is undefined. You can either bind it yourself, or just make it a regular function like I did below.

Also, make sure to return a value from MyClass.prototype.take(), or else you'll get undefined.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const MyClass = (function() {
  function MyClass() {
    this._obj = {
      1: &#39;dfvdfvd&#39;
    };
  }

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

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

  return MyClass;
}());

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 08:33:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定