【问题标题】:Canvas object and multiple instances inside another object?画布对象和另一个对象内的多个实例?
【发布时间】:2013-05-14 11:11:42
【问题描述】:

我有一个画布对象,我可以这样调用

var canvas = new Canvas();

canvas 对象在其原型中也有很多功能。该对象本质上创建了一个画布元素,具有一些功能,例如setWidthgetContext 等。

我还有一个Layer 对象,它本质上是一个具有附加功能的画布。我认为将Layer 的原型设置为Canvas 是个好主意。这很好用,一切都很好。

当我想使用多个图层时,问题就开始了,因为每个图层都应该有自己的画布。但是由于canvas是Layers原型,这个原型只指向一个canvas元素。因此,当我开始使用多个图层时,画布总是会被覆盖,因为图层原型中的画布元素指向同一个画布对象。

我希望到目前为止我是有道理的!

我知道我可以将画布作为一个属性添加到图层中,但不是这样做,

layer.setWidth(900);

我不得不这样做

layer.canvas.setWidth(900);

我想我的问题是,我怎样才能继承 Canvas 对象函数但在实例化一个新层时让它用它创建一个新的画布元素?

根据要求提供代码(简体)

var carl = {};

carl.Canvas = (function() {

     "use strict";

     function Canvas(config) {

          this._init(config);
     };

     Canvas.prototype._init = function(config) {

         this.element = document.createElement("canvas");
         this.context = this.element.getContext("2d");
     };

     Canvas.prototype.setWidth = function(width) {

         this.element.width = width;
     };

     Canvas.prototype.getWidth = function() {

         return this.element.width;
     };

     Canvas.prototype.setHeight = function(height) {

         this.element.width = height;
     };

     Canvas.prototype.getHeight = function() {

         return this.element.height;
     };

     Canvas.prototype.getContext = function() {

         return this.context;
     };

     return Canvas;
}}();

 carl.Layer = (function() {

     "use strict";

      function Layer() {

      };

      Layer.prototype = new carl.Canvas();

      return Layer;

 })();

【问题讨论】:

    标签: javascript object prototype


    【解决方案1】:

    你只需要:

    carl.Layer = function() {
         carl.Canvas.call(this);
    };
    carl.Layer.prototype = Object.create(carl.Canvas.prototype);
    

    停止使用立即调用的函数和闭包以及其他类似的东西引入大量开销。它们完全没用。保持代码干净。如果你不想要Object.create,你可以使用polyfill。

    function inherits(child, parent) {
        function temp() {};
        temp.prototype = parent.prototype;
        child.prototype = new temp();
        child.prototype.constructor = child;
    };
    carl.Layer = function() {
         carl.Canvas.call(this);
    };
    inherits(carl.Layer, carl.Canvas);
    

    【讨论】:

    • 我需要在 IIFE 中使用我的代码,感谢您的回答,我现在就试试 :)
    猜你喜欢
    • 2018-12-13
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2012-07-07
    • 2019-05-18
    • 2013-12-17
    相关资源
    最近更新 更多