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

问题描述 投票:0回答:2

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://stackoverflow.com/questions/ask#</script>

CodePen

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

我的目标是在没有声明的情况下将method1's parameter分享给method2。如果method1's parameter没有参数,我想在屏幕上假设method2。结果就像是;

这是参数Orange // method1的结果 这是另一个参数Orange // method2的结果

如果method2有自己的参数:

这是参数Orange // method1的结果 这是另一个参数Blue // method2的结果

我已经尝试了几种方法来获得任何类型的线索,但根本没有进展。

有没有办法做到这一点?

javascript variables data-structures parameters prototype
2个回答
1
投票

以下是如何通过课程完成的

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>

1
投票

无需使用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://stackoverflow.com/questions/ask#</script>

请注意,这将为任何虚假值提供回退。因此,如果你想故意通过nullundefined""(空字符串)或0,你会得到后备。

© www.soinside.com 2019 - 2024. All rights reserved.