2012-08-01 20 views
2

我有這個代碼,它的工作。如何將這個結合到一個JavaScript對象?

var URL = new Object(); 

URL.pattern = /https?:\/\/([^\/]*)\//; 
URL.current = window.location.href; 

URL.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
}; 

var thisDomain = URL.getCurrent(); 

現在我想要的是將點符號放入對象,我該怎麼做?我試過這個,但是當我調用URL.getCurrent()時它顯示爲undefined。

function URL(){ 

    this.pattern = /https?:\/\/([^\/]*)\//; 
    this.current = window.location.href; 

    this.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
    }; 
} 

我希望有人能幫助我。

+1

另外,我希望你至少勾選一個答案這個時候 – Alexander 2012-08-01 06:41:15

+0

對不起你們,我不知道。我從現在開始接受他們。 =) – reitermarkus 2012-08-01 06:57:58

回答

5

您可以做的最簡單的事情就是將它放在對象字面上。

http://jsfiddle.net/wJQb6/

var URL = { 
    pattern: /https?:\/\/([^\/]*)\//, 
    current: window.location.href, 
    getCurrent: function() { 
     return this.current.match(this.pattern)[1]; 
    } 
} 

alert(URL.getCurrent());​ 
+0

贏得文字註釋。我不確定OP需要什麼,這看起來更像是對原始代碼的重寫,無論如何,這是更有效的,而OP所嘗試的內容很可能是不可能的(您不能像訪問函數對象的嵌套函數常規對象)。 – 2012-08-01 06:44:23

+0

嗯,已經試過文字註釋,也沒有工作。但現在它正在工作! – reitermarkus 2012-08-01 06:47:54

+0

是的,它是原始的重寫。 – reitermarkus 2012-08-01 06:50:07

1

您仍然需要實例。

var url = new URL; 
+0

好吧,現在我知道了。我想每個人都是初學者。 =) – reitermarkus 2012-08-01 06:48:34

0

如果您需要使用經典的OOP你可以做這樣的事情:

function URL(){ 
    /* constructor function */ 
} 

URL.prototype.pattern = /https?:\/\/([^\/]*)\//; 
URL.prototype.current = window.location.href; 

URL.prototype.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
}; 

anURL = new URL(); 
var result = anURL.getCurrent(); 
+0

模式也可以在原型上(請參閱我的回答) – Bergi 2012-08-01 06:50:53

+0

同意。只是感動:) – 2012-08-01 06:51:43

+0

...但空的構造函數看起來很奇怪。 – Bergi 2012-08-01 06:53:06

2
function URL(){ 
    this.pattern = /https?:\/\/([^\/]*)\//; 
    this.current = window.location.href; 
    this.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
    }; 
} 

有了這個,你有一個空的構造。該功能URL本身沒有屬性,你需要創建一個實例:

var url = new URL; 
url.getCurrent(); 

然而,我建議下面的構造,其中包括繼承:

function URL(c){ 
    this.current = c; 
} 
URL.prototype.pattern = /https?:\/\/([^\/]*)\//; 
URL.prototype.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
}; 

// Usage: 

var url = new URL(window.location.href); 
url.getCurrent(); 

如果你想有一個靜態對象,只是使用對象文字:

var url = { 
    pattern: /https?:\/\/([^\/]*)\//, 
    current: window.location.href, 
    getCurrent: function() { 
     return this.current.match(this.pattern)[1]; 
    } 
} 

url.getCurrent(); 
+0

謝謝,靜態對象是我想要的。 – reitermarkus 2012-08-01 07:08:43

1

JavaScript中沒有靜態方法,但可以使用單例。

var URL=new function(){ 

    this.pattern = /https?:\/\/([^\/]*)\//; 
    this.current = window.location.href; 

    this.getCurrent = function(){ 
    return this.current.match(this.pattern)[1]; 
    }; 
}; 

這將允許您訪問URL proptotype和構造函數,如果需要它們。

相關問題