Javascript 单例继承

Has*_*avi 5 javascript oop inheritance singleton

我想保留一个单亲类。继承父类的所有 clild 类将能够共享相同的父类对象。如何实现?

var ParentClass = function(){
    this.a = null;
}

ParentClass.prototype.setA = function(inp){
    this.a = inp;
}

ParentClass.prototype.getA = function(){
    console.log("get a "+this.a);
}

// Clild Class

var ClassB = function(){}

ClassB.prototype = Object.create(ParentClass.prototype);

var b = new ClassB();
b.setA(10);
b.getA(); //it will return 10


//Another clild Class
var ClassC = function(){}

ClassC.prototype = Object.create(ParentClass.prototype);
var c = new ClassC();
c.getA(); //I want 10 here.
Run Code Online (Sandbox Code Playgroud)

我明白,对于第二个 clild 类,父类再次实例化,这就是我无法访问旧对象的原因。如何在 Javascript 中实现这种单例继承?任何的想法?

Ber*_*rgi 3

将此类静态值放在其他地方。this是当前实例,这不是您要创建新属性的位置。选项有:

  • ParentClass.prototype(如 @bfavaretto 所示),这将导致所有实例继承并能够覆盖它
  • 作用域变量(基本上实现揭示模块模式):

    (function() {
        var a;
        ParentClass.prototype.setA = function(inp){
            a = inp;
        };
        ParentClass.prototype.getA = function(){
            console.log("get a "+a);
            return a;
        };
    }());
    
    Run Code Online (Sandbox Code Playgroud)
  • 函数ParentClass对象本身:

    ParentClass.prototype.setA = function(inp){
        ParentClass.a = inp;
    };
    ParentClass.prototype.getA = function(){
        console.log("get a "+ParentClass.a);
        return ParentClass.a;
    };
    
    Run Code Online (Sandbox Code Playgroud)