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

问题描述:

只有纯香草JS代码。没有jQuery或其他外部的东西,谢谢。 :)功能与子功能,但也有它自己的...功能...?

如何创建一个包含子函数的函数,并且在没有子函数被调用的情况下返回一个值?

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

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

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

现在我的魔杖轮()有子功能是将圆向上或向下,不顾十进制值。

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方面如此薄弱,以至于我不知道正确的术语......当然,这并不能帮助我们寻找线索,或者知道任何可能的原因不应该工作...

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

+0

您不能将round定义为一个函数,并且在具有两个函数('up'和'down')的对象的相同位置。 –

+0

只有构造函数默认具有'prototype'属性。 '4.12'不是一个对象,更不是一个构造函数。 – Oriol

+2

基本上,问题是当你调用'num.round.up'时,'this'值将是'num.round'函数,而不是'num'。然后我不推荐这种方法。更好地允许'num.round'接收可选参数,并将其称为'num.round()','num.round('up')'或'num.round('down')'。 – Oriol

可能是这样的:

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

也许我应该明确指出,我希望在。之后有.up/.down函数。第一回合。就因为这个原因,你的建议不适合我。 另外,当你设置num并且返回静态值时,你不会计算一切吗?我绝对不会找那个,对不起。 – Rob

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

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