简体   繁体   English

如何在JavaScript中实现抽象工厂方法?

[英]How to implement abstract factory method in JavaScript?

So how to use abstract factory method in JavaScript? 那么如何在JavaScript中使用抽象工厂方法呢? For example in Java: 例如在Java中:

public abstract class SuperClass {
    abstract String bar();

    public String foo() {
        return bar();
    }
}

public class SubClass extends SuperClass{
    @Override
    String bar() {
        return "bar";
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new SubClass().foo());
    }
}

It shows bar and just fine. 它显示bar ,就好了。 But when I tried this in JavaScript: 但是,当我在JavaScript中尝试此操作时:

var SuperClass = function () {};
SuperClass.prototype.foo = function () {
    return this.prototype.bar();
};

var SubClass = function () {};
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;

SubClass.prototype.bar = function () {
    return "bar";
};

var myClass = new SubClass();
console.log(myClass.foo());

I get Uncaught TypeError: Cannot read property 'bar' of undefined . 我收到Uncaught TypeError: Cannot read property 'bar' of undefined I tracked the bug and turns out, when SuperClass.prototype.foo is being executed, SubClass.prototype is still undefined . 我跟踪了该错误,结果发现,当执行SuperClass.prototype.foo时, SubClass.prototype仍未undefined

So, what's the right way to do that? 那么,什么是正确的方法呢? Thanks you! 谢谢!

You should not access bar on the prototype. 您不应访问原型上的bar Just access it on the instance: 只需在实例上访问它:

return this.bar();

You can access the prototype of an object through the __proto__ field. 您可以通过__proto__字段访问对象的原型。 So, if you change : 因此,如果您更改:

SuperClass.prototype.foo = function () {
    return this.prototype.bar();
};

with : 与:

SuperClass.prototype.foo = function () {
    return this.__proto__.bar();

};

your example works. 您的示例有效。 You can also use: 您还可以使用:

return Object.getPrototypeOf(this).bar();
return this.constructor.prototype.bar();

But, you can just call return this.bar() and the prototype traversal will be executed automatically by Javascript, until the method is found in the prototype chain. 但是,您只需调用return this.bar() ,原型遍历将由Javascript自动执行,直到在原型链中找到该方法为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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