2

私はこのコードを持っており、それは機能しています。

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];
  };
}

誰かが私を助けてくれることを願っています。

4

5 に答える 5

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());​
于 2012-08-01T06:41:52.140 に答える
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();
于 2012-08-01T06:48:15.240 に答える
1

まだインスタンス化する必要があります。

var url = new URL;
于 2012-08-01T06:40:39.287 に答える
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 とコンストラクターにアクセスできるようになります。

于 2012-08-01T07:00:37.383 に答える
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();
于 2012-08-01T06:47:23.953 に答える