我将如何在这两个函数之间共享参数?

How would I share the parameters between these 2 functions?

const a = {
  method1: function(param) {
    this.param = param;
    $('span[data-count]').text('This is a parameter ' + param);
  },
  test: 10
}
var b = Object.create(a);
b.method2 = function(param) {
  this.param = param;
  $('.span2[data-count]').text('This is an another parameter ' + b.param);
}

b.method1('Orange');
b.method2('Blue');
    <span data-count></span><br>
    <span data-count class="span2"></span>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">https://whosebug.com/questions/ask#</script>

CodePen

我有一个名为 a 的对象,它是另一个名为 b 的对象的原型。执行这些时,每个结果将显示不同的标签 span.span2.

我的目标是将 method1's parameter 分享给 method2 而无需 if 语句 。当 if method2 没有参数时,我想在屏幕上假设 method1's parameter 。所以结果就像;

This is a parameter Orange // method1's result
This is an another parameter Orange // method2's result

如果method2有自己的参数:

This is a parameter Orange // method1's result
This is an another parameter Blue // method2's result

我尝试了多种方法来获取各种线索,但毫无进展。

有什么办法吗?

这是使用 class

的方法

const foo = new class {
  method1(param) {
    $(`span[data-count]`).text(`This is a parameter ${this.param = param}`)
  }
  
  method2(param = this.param) {
    $(`.span2[data-count]`).text(`This is an another parameter ${this.param = param}`)
  }
}

foo.method1('Orange');
foo.method2();
<span data-count></span><br>
<span data-count class="span2"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

因此使用您的方法,我们给 method2 一个默认值 this.param

const a = {
  method1: function(param) {
    this.param = param;
    $('span[data-count]').text('This is a parameter ' + param);
  },
  test: 10
}

var b = Object.create(a);
b.method2 = function(param = this.param) {
  this.param = param;
  $('.span2[data-count]').text('This is an another parameter ' + b.param);
}

b.method1('Orange');
b.method2();
<span data-count></span><br>
<span data-count class="span2"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

不用 使用if 语句,你可以轻松地 得到你想要的东西。如果没有传入参数,您可以使用 logical OR 提供回退。回退将是 this.param ,它是在调用任一方法时设置的,因此另一个方法仍将使用相同的值。

const a = {
  method1: function(param) {
    param = param || this.param; //provide a fallback if `param` is falsey
    this.param = param;
    $('span[data-count]').text('This is a parameter ' + param);
  },
  test: 10
}
var b = Object.create(a);
b.method2 = function(param) {
  param = param || this.param; //provide a fallback if `param` is falsey
  this.param = param;
  $('.span2[data-count]').text('This is an another parameter ' + b.param);
}

b.method1('Orange');
b.method2(); //nothing passed in
<span data-count></span><br>
    <span data-count class="span2"></span>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">https://whosebug.com/questions/ask#</script>

请注意,这将为任何 falsey 值提供回退。因此,如果您想有意传递 nullundefined""(空字符串)或 0,您将获得回退。