I tried to create an object that inherits from the context object. But after calling the function from the object that I inherit from, the browser (Chrome) points to Uncopy TypeError: Illegal call . Here is the basic code:
http://jsfiddle.net/adrianh/BKYfv/1/
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var ctx2 = Object.create(ctx);
ctx.setTransform(1, 0, 0, 1, 0, 0);
alert("ctx works");
ctx2.setTransform(.5, 0, 0, .5, 0, 0);
alert("ctx2 works");
Why is this failing?
Bypass
I wrote a function makeForwardingObject()that does what I want. You can find it here.
function makeForwardingObject(obj, funcs, attribs)
{
var _ = { };
Object.defineProperties(_, {
_: { value: obj },
applyParent : { value: function applyParent(func, args)
{
return this._[func].apply(this._, args);
}},
callParent: { value: function callParent(func)
{
var args=[];
for (i=1; i<arguments.length; ++i)
args[i-1]=arguments[i];
return this._[func].apply(this._, args);
}},
setParentAttrib: { value: function setParentAttrib(attrib, val)
{
return this._[attrib]=val;
}},
getParentAttrib: { value: function getParentAttrib(attrib, val)
{
return this._[attrib];
}},
});
for (var key in obj)
{
switch (typeof obj[key])
{
case 'function':
_[key] = eval("(function "+key+"() { return this._."+key+".apply(this._, arguments); })");
break;
default:
eval("Object.defineProperty(_, '"+key+"', {"+
"get: function "+key+"() { return this._."+key+"; },"+
"set: function "+key+"(v) { return this._."+key+"=v; },"+
"enumerable: true,"+
"})");
break;
}
}
for (var index in funcs)
{
var key = funcs[index];
if (!_.hasOwnProperty(key))
{
_[key] = eval("(function "+key+"() { return this._."+key+".apply(this._, arguments); })");
}
}
for (var index in attribs)
{
var key = funcs[index];
if (!_.hasOwnProperty(key))
{
eval("Object.defineProperty(_, '"+key+"', {"+
"get: function "+key+"() { return this._."+key+"; },"+
"set: function "+key+"(v) { return this._."+key+"=v; },"+
"enumerable: false,"+
"})");
}
}
return _;
}
function getMembers(obj)
{
var _ = "";
for (key in obj)
{
_ += key + ":" + typeof obj[key] + " = " + obj[key] +"\n";
}
return _;
}
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var ctx2 = makeForwardingObject(ctx);
var x = { a: "" };
alert(getMembers(ctx));
alert(getMembers(ctx2));
ctx.setTransform(1, 0, 0, 1, 0, 0);
alert("ctx works");
ctx2.setTransform(.5, 0, 0, .5, 0, 0);
alert("ctx2 works");
ctx2.moveTo(0,0);
ctx2.lineTo(100, 100);
ctx2.stroke();