【问题标题】:Function with sub-functions but also its own... function...?具有子功能的功能,但也有自己的...功能...?
【发布时间】:2016-06-08 17:49:31
【问题描述】:

只有纯原生 JS 代码。没有 jQuery 或其他外部的东西,谢谢。 :)

如何创建一个包含子函数但如果没有调用子函数也返回一个值的函数?

例如,我们取一个数字变量 num。

我想给 number 变量添加一个 round() 函数;如果直接调用,我希望它根据变量的实际值向上或向下舍入。

var num=4.12;
num.prototype.round=function(){return Math.round(this);}

现在我希望 round() 具有向上或向下舍入的子函数,而忽略十进制值。

num.prototype.round.up=function(){return Math.ceil(this);}
num.prototype.round.down=function(){return Math.floor(this);}

如果我这样做并将 num.round() 记录到控制台,它会做它应该做的事情。但是如果我将 num.round.up() 记录到控制台,我会收到一条错误消息,告诉我 num.round.up() 不是一个函数。

所以我尝试将子函数放入主函数声明中,如下所示:

num.prototype.round=function(){
    var n=this;
    this.up=function(){return Math.ceil(n);}
    this.prototype.round.down=function(){return Math.floor(n);}
    return Math.round(n);
}

然后,num.round() 将返回正确舍入的值,但 num.round.up() 和 num.round.down() 都会返回“不是函数”错误。

我想弄清楚这一点我快疯了……我不仅尝试了上面提到的方法,而且还尝试通过立即执行如下函数来做到这一点:

num.round=(function(){
    return function(){
        var that=this;
        /* anything in here is already useless because this
        is no longer num's value but [Object window]... */
    }
})();

我想部分问题是我在 OOP 方面太弱了,以至于我对正确的术语一无所知......当然,这在寻找线索或了解任何潜力时都无济于事为什么这样的事情不应该工作的原因......

那么有什么办法可以做到这一点吗?

【问题讨论】:

  • 您不能将 round 定义为一个函数,并且不能将其定义为一个包含两个函数(updown)的对象。
  • 默认情况下,只有构造函数具有prototype 属性。 4.12 不是对象,更不是构造函数。
  • 基本上,问题是当您调用num.round.up 时,this 的值将是num.round 函数,而不是num。那我不推荐这种方法。最好允许num.round 接收一个可选参数,并将其命名为num.round()num.round('up')num.round('down')
  • "那么有什么办法可以做到这一点吗?" - 是的,但不是一个好的或 OOP 的。
  • @Bergi 你能指出我正确的方向吗?我无意制作此功能或任何可继承的功能等等。它应该只在一个地方服务于一个目的。

标签: javascript function object methods


【解决方案1】:

可能是这样的:

function num(n) {
    this.num=n;
    this.round=Math.round(n);
    this.up=Math.ceil(n);
    this.down=Math.floor(n);
    this.up2=function(){return Math.ceil(n);}
}
var num = new num(4.12);
alert(num.num);
alert(num.round);
alert(num.up);
alert(num.down);
alert(num.up2());

【讨论】:

  • 也许我应该明确指出,我希望在 .round 函数“之后”拥有 .up/.down 函数。正因为如此,你的建议对我不起作用。另外,您所做的不是在设置 num 时只计算一次然后返回静态值吗?抱歉,我绝对不是在寻找那个。
【解决方案2】:

你可以给函数传递一个参数。不是您想要的确切实现,只是一个替代方案:

var num = function (defaultNumValue) {
  var delegation = {
    'up': 'ceil',
    'down': 'floor'
  };
  return {
    round: function (val) {
      return Math[ delegation[val] || 'round' ](defaultNumValue); 
    }
  }
};

var sth = num(1.5);
sth.round(); // 2
sth.round('up'); // 2
sth.round('down'); // 1

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2018-11-23
    • 2018-10-19
    • 1970-01-01
    相关资源
    最近更新 更多