繁体   English   中英

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

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

我希望有人可以帮助我。

你能做的最简单的事情就是把它放在一个对象字面上。

http://jsfiddle.net/wJQb6/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM