在JavaScript中使用原型名称中的“点”

时间:2012-03-01 09:23:18

标签: javascript prototype

让我说我有这个课程:

function classA(n){
    this.name = n
}

classA.prototype.getName = function(){
    return this.name
}

var x = new classA('john')
console.log(x.getName())

我的问题是:我可以在命名空间内对多个方法进行分组吗?所以我想这样做:

var x = new classA('john')
console.log(x.CONSTANT.getName())

所以我想将一些方法称为x.someMethod(),将其他方法称为x.CONSTANT.otherMethod()

PS:我正在寻找一种跨浏览器的方法。绑定在Safari和IE9中不起作用。

4 个答案:

答案 0 :(得分:3)

您可以通过bind执行此操作。 Google es5 shim用于在浏览器中实现绑定,这些浏览器本身不支持它。

function MyClass(name) {
   this.name = name;
   this.CONSTANT.otherMethod = this.CONSTANT.otherMethod.bind(this);
}
MyClass.prototype.CONSTANT = {
   otherMethod: function() {
        alert(this.name);
   }
};

答案 1 :(得分:1)

据我所知,常量只是一个属性而且它不能包含方法,你需要分离你的对象并使用方法来产生同样的效果:

function A (id) {

    this.id = id;
    this.showId = function () { return this.id; }
};

function B (a) {

    this.a = a;
    this.getA = function () { return this.a; }
}

var a = new A(12);
var b = new B(a);

b.getA().showId();

修改 您可以使用文字对象,如下所示

function B (id) {

  this.id = id;
  this.CONSTANT = { otherMethod: function () { alert("..."); } };
  someMethod = function () { return this.id; }
}

但文字CONSTANT对象无法访问B对象方法,

考虑@kirilloid帖子来围绕这个。

答案 2 :(得分:0)

你可以,但你必须小心,因为它不会像你认为的那样行事。方法的this将是命名空间,而不是根对象。 例如,在x.CONSTANT.getName()中,this对象将是x.CONSTANT,而不是x

以下是一些示例代码,它们可以满足您的要求(或in jsfiddle):

function MyClass() {}

MyClass.prototype.CONSTANT = {
    getName: function() {
        alert('Foo');
    }
};


var c = new MyClass();
c.CONSTANT.getName();

要确保this正确,您需要做更多事情。

答案 3 :(得分:-1)

您可以使用getter / setter(读取this article)来实现此目的。例如,您可以这样定义:

classA.prototype.__defineGetter__('CONSTANT', function() {
    var that = this;
    return {
        getName: function() {
            return that.name;
        }
    };
});

注意that持有对象的引用。它现在可以使用了

x = new classA('test');
x.CONSTANT.getName();
// result - test