[英]How to Combine Same key JavaScript Object to one Array Dynamically
[英]How to combine this to one javascript Object?
我有這個代碼,它正在運行。
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];
};
}
我希望有人可以幫助我。
你能做的最簡單的事情就是把它放在一個對象字面上。
var URL = {
pattern: /https?:\/\/([^\/]*)\//,
current: window.location.href,
getCurrent: function () {
return this.current.match(this.pattern)[1];
}
}
alert(URL.getCurrent());
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();
你仍然需要實例化。
var url = new URL;
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和contructor。
如果你需要使用經典的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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.