如何将其与一个javascript对象组合?

时间:2012-08-01 06:37:16

标签: javascript object syntax

我有这个代码,它正在运行。

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()时它显示未定义。

function URL(){

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

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

我希望有人可以帮助我。

5 个答案:

答案 0 :(得分: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());​

答案 1 :(得分: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();

答案 2 :(得分:1)

你仍然需要实例化。

var url = new URL;

答案 3 :(得分: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和构造函数。

答案 4 :(得分: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();