Can't inherit from context object?

后端 未结 1 1430
野性不改
野性不改 2021-01-13 12:50

I was trying to create an object that inherits from the context object. But upon calling a function from the object that I\'m inheriting from, the browser (Chrome) states <

相关标签:
1条回答
  • 2021-01-13 13:22

    One shallow answer would be because a canvas rendering context can't be constructed. Using the CanvasRenderingContext2d() function (like many other constructors in the DOM) will throw an Type error: "Illegal constructor", because they are supposed to only be created in one specific way from a factory function. In this case the .getContext() method of the canvas.

    Despite creating a new Object with a RenderingContext2d as a prototype you can falsely create a rendering context by using

    ctx2=Object.create(CanvasRenderingContext2D.prototype);
    

    or

    ctx2=Object.create(ctx.constructor.prototype);
    

    Giving you a completely blank stateless (and useless) rendering context object, which actually throws the same exceptions as your cloned context. It doesn't even have a canvas assigned.

    The reason this doesn't work is because you only inherit a reference to the the public methods of the RenderingContext prototype, and in your case of the clone has a reference to all the states of the context you created it from via prototype chain, but other than that it's a hollow body. No private var and no privately declared function declared inside the CanvasRenderingContext constructor gets inherited via the prototype.

    In case you are curious, you can write this kind of object yourself

    function nonConstructable(factoryVar){
        if(arguments.callee.caller !== Factory){
            throw TypeError("Invalid constructor");
        }
        var privateVar = privateMethod();
        privateVar+=factoryVar;
        this.publicVar= privateVar;
    
        function privateMethod(){
            return 123;
        }
    }
    function Factory(){
        var privateFactoryVar = 321;
        return new nonConstructable(privateFactoryVar );
    }
    

    You see this way these 2 objects are linked and the only way for you to execute the operations inside the nonConstructable constructor is by constructing it via the specific Factory.

    Doing a bit of more research it seems CanvasRenderingContext2D and WebGLRenderingContext are planned to be valid constructors for contexts, who can just render to any canvas and should both work inside a worker thread. I couldn't find out what the current state of the implementation is through, seems like people completely stopped writing about it 2 years ago for some reason.

    0 讨论(0)
提交回复
热议问题