2016-02-25 218 views
2

只有純香草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

回答

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

也許我應該明確指出,我希望在。之後有.up/.down函數。第一回合。就因爲這個原因,你的建議不適合我。 另外,當你設置num並且返回靜態值時,你不會計算一切嗎?我絕對不會找那個,對不起。 – Rob

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