功能与子功能,但也有自己的......功能......?

时间:2016-02-25 19:01:52

标签: javascript function object methods

只有纯粹的香草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()都将返回“not a function”错误。

我想解决这个问题......我不仅尝试了上面提到的内容,而且还试着立即执行这样的功能:

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上如此虚弱,以至于我对正确的术语一无所知......当然,这在寻找线索或知道任何潜力时都无济于事这样的事情不应该起作用的原因......

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

可能是这样的:

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