2013-02-17 64 views
2

起作用,我可以與其它功能類似所以它擴大:的javascript:加法功能如果我在「構造」添加在函數內部.prototype = {

var MyClass = function() { 
    this.time = function() { return 4.5; } 
    this.time.formatted = function() { return format(this.time(), "HH:mm"); } 
} 

我不能找出一個如果我在原型創建函數像這樣漂亮的方式做到這一點:

var MyClass = function() {} 
MyClass.prototype = { 
    time: function() { return 4.5; }, 
    time.formatted: function() { ... } // This does not work! 
} 


MyClass.prototype.time.formatted = function() { ... } 
// the line above works but I don't like it since it separates everything. 
// e.g. if I have 15 functions inside prototype, the .formatted will be like 
// 50 lines apart from the time: function 

*編輯:*退一步線以上不工作,加入.formatted混亂 提及這一點。也許可以解決?

任何提示?謝謝!

+0

做到這一點的唯一方法是後者;對象文字符號不支持該語法。 – Matt 2013-02-17 10:08:38

+2

你爲什麼不創建第二堂課?然後只是做'this.time = new TimeFormatter();' – Prinzhorn 2013-02-17 10:08:42

+0

這是Decorator模式的新方法:( – dfsq 2013-02-17 10:11:36

回答

2

創建原型對象之前創建的功能,它允許你爲它添加一個屬性,並且還可以讓你在不使用的情況下使用該功能:

function MyClass() {} 

function time() { return 4.5; } 
time.formatted = function() { return format(time(), "HH:mm"); } 

MyClass.prototype = { 
    time: time; 
} 

你可以把它放在一個函數表達式,以保持它在一起,並避免在全球範圍內的time功能:

function MyClass() {} 
MyClass.prototype = (function(){ 

    function time() { return 4.5; } 
    time.formatted = function() { return format(time(), "HH:mm"); } 

    return { 
    time: time; 
    } 

})(); 

注:formatted功能將稱爲常規函數,而不是作爲對象的方法。這意味着從formatted函數調用函數time時無法訪問this

如果您需要這樣做,那麼原型中就不能有time函數。類的每個實例都需要它自己的time功能,其中formatted酒店訪問對象的特定實例的版本:

function MyClass() { 

    this.theTime = 4.5; 

    this.time = function() { return this.theTime; } 

    var t = this; 

    this.time.formatted = function() { return format(t.time(), "HH:mm"); } 

} 
1

此代碼不起作用:

var MyClass = function() { 
    this.time = function() { return 4.5; } 
    this.time.formatted = function() { return format(this.time(), "HH:mm"); } 
} 

var m = new MyClass(); 
console.log(m.time.formatted()) 

因爲this.formattedm.time,不m。您應該使用:

var MyClass = function() { 
    this.time = function() { return 4.5; } 
    this.time.formatted = function() { return format(this(), "HH:mm"); } 
} 

var MyClass = function() { 
    var self = this; 
    this.time = function() { return 4.5; } 
    this.time.formatted = function() { return format(self.time(), "HH:mm"); } 
} 

回答您的實際問題,讓一個輔助函數:

var callable(f, props) { 
    for(p in props) f[p] = props[p]; 
    return f; 
} 

MyClass.prototype = { 
    time: callable(function() { 
     return 4.5; 
    }, { 
     formatted: function() { return format(this(), "HH:mm"); } 
    }) 
} 
相關問題