javascript - 自定义元素继承

标签 javascript html web-component

我似乎触发了生命周期回调,但我无法访问母类属性。

例如我有这个自定义元素:

var Game = document.registerElement('x-game', {
    prototype: Object.create(HTMLElement.prototype, {
        cards: {
            value: [],
            writable : true,
            enumerable : true,
        },
        createdCallback: {
            value: function () {
                this.cards = deck();
            }
        }
    })
});

使用 deck() 函数来填充我的数组。

我想创建一个继承前者的另一个元素:

var Golf = document.registerElement('x-golf', {
    prototype: Object.create(Game.prototype, {
        columns: {
            value: []
        },
        waste: {
            value: new Waste
        },
        talon: {
            value: new Talon
        },
        createdCallback: {
            value: function () {    
                Game.prototype.createdCallback.apply();
                this.initialize();
            }
        },
        initialize: {
            value : function () {
            for (var i = 0; i < 7; i++) {
                var column = new Column;
                for (var r = 0; r < 5; r++){
                    column.cards[r] = this.cards.pop();
                }
                this.columns[i] = column;
            }
            this.waste.cards.push(this.cards.pop());
            for (var j = 0; j < this.cards.length; j++){
                var card = this.cards.pop();
                card.side = 'verso';
                this.talon.cards[j] = card;
            }
        }
    })
});

通常使用 Game.prototype.createdCallback.apply(); 应该填充新 x-golf 元素上的 cards 属性,但事实并非如此。控制台上card属性的值仍然是一个空数组,为它的默认值。

那么如何确保在父类(super class) createdCallback 的调用中正确填充卡片属性?

最佳答案

您缺少 .apply() 调用的目标:

Game.prototype.createdCallback.apply(this);

工作 jsbin .

关于javascript - 自定义元素继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097529/

相关文章:

Angular Web 组件捆绑外部自定义字体包

javascript - 如何从浏览器编辑和保存静态网页?

javascript - 将 jQuery 'rand color' 保存到本地存储?

java - 从 html &lt;script&gt;-node 运行 Java 代码

javascript - CSS样式{显示:none} is not working in htmlattribute

reactjs - 如何在没有 iFrame 的情况下制作 Javascript 小部件?

javascript - 为什么 Angular 根范围变量仅在两次单击事件按钮后才更新?

javascript - 在 asyncStorage 中存储数组状态对象

html - 路径错误如何解决?

javascript - 自定义元素的属性可以驼峰式吗?