2

我的“基类”似乎没有正确填充。为什么?

<script type="text/javascript">

    var exceptions = {
        NotImplementedException: function (message) {
            this.name = 'NotImplementedException';
            this.message = message || 'Property or method is not implemented.';
        }
    };
    exceptions.NotImplementedException.prototype = Error.prototype;

    function ActionButton() {
        this.execute = function () {
            throw new exceptions.NotImplementedException("Execute is not implemented.");
        };
        this.render = function (data) {
            throw new exceptions.NotImplementedException("Render is not implemented.");
        };
        this.$template = function () {
            throw new exceptions.NotImplementedException("$template is not implemented.");
        };
    };

    function ImageActionButton() {
        this.image = { url: '' };
    };
    function TextActionButton() {
        this.text = '';
    };
    function StandardActionButton() {
        this.text = '';
        this.image = { url: '' };
    };
    function MenuActionButton() {
        this.buttons = [];
    };

    ImageActionButton.prototype = new ActionButton();
    ImageActionButton.prototype.constructor = ImageActionButton;

    TextActionButton.prototype = new ActionButton();
    TextActionButton.prototype.constructor = TextActionButton;

    StandardActionButton.prototype = new ActionButton();
    StandardActionButton.prototype.constructor = StandardActionButton;

    MenuActionButton.prototype = new ActionButton();
    MenuActionButton.prototype.constructor = MenuActionButton;

    // This fails
    if (ImageActionButton.prototype != ActionButton) {
        alert("ImageActionButton prototype is not ActionButton!");
    }
    // This works
    if (ImageActionButton.prototype.constructor != ImageActionButton) {
        alert("ImageActionButton prototype.constructor is not ImageActionButton!");
    }
</script>
4

1 回答 1

2

我认为你会想要使用instanceof而不是像你一样进行比较。

if (ImageActionButton instanceof ActionButton) {
    alert("ImageActionButton prototype is not ActionButton!");
}
于 2012-12-24T02:14:31.020 回答