简体   繁体   English

在对象文字的声明中继承上下文(此)? 自我可以吗?

[英]Inherit context (this) in the declaration of an object literal? Is `self` okay?

Is it posisble to remove the self variable in this snippet: 在此代码段中删除self变量是否可疑:

class Foobar {
  constructor() {
    let self = this; // How do I remove self?
    let fizz = buzz.doSomething({
      aFunction: self.someFun 
    });
  }

  someFun() {
  }
}

One option could be to define an empty object and then assign the function with the key. 一种选择是定义一个空对象,然后为功能分配键。

let options = {};
options[aFunction] = this.doSomething;
let fizz = buzz.doSomething(options);

If the options object becomes a list of 10 things wouldn't be better to have them all wrapped by a single pair of braces? 如果options对象成为10个对象的列表,将它们全部都用一对大括号包裹会更好吗?

Am I overthinking it? 我在想什么吗?

You can safely use this in your code snippet. 您可以在代码段中安全地使用this this only changes it's meaning when you're invoking a function using the function(){} syntax. 仅当您使用function(){}语法调用函数时, this改变它的含义。 In your case you're just creating an object literal, where this is still the same as self . 在您的情况下,您只是在创建对象文字,而this文字仍然与self相同。

constructor() {
    let fizz = buzz.doSomething({
       aFunction: this.someFun 
    });
}

This works perfectly fine. 这工作得很好。 Even made a jsfiddle . 甚至做了jsfiddle

If you want to go into more depth check out this on the MDN. 如果你想进入更深入检查出对MDN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM