[英]getOwnPropertyDescriptor of redefined toString should be undefined
I have redefined toString
of HTMLCanvasElement.prototype.toDataURL
.我重新定义了
HTMLCanvasElement.prototype.toDataURL
toString
。 When I am getting property descriptor of toString
it should return undefined
, but it returns the function.当我获取
toString
属性描述符时,它应该返回undefined
,但它返回函数。 Any ideas how to fix it?任何想法如何解决它?
You can execute code here https://jsfiddle.net/nqk50a8r/你可以在这里执行代码https://jsfiddle.net/nqk50a8r/
Object.defineProperty(HTMLCanvasElement.prototype.toDataURL, 'toString', {
value: function () { return 'function toDataURL() { [native code] }';}
});
var desc = Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype.toDataURL, 'toString');
console.log(desc === undefined);
If you removed defineProperty
block you will see that it returns undefined
.如果您删除了
defineProperty
块,您将看到它返回undefined
。
I redefined toDataURL
by next code:我通过下一个代码重新定义了
toDataURL
:
Object.defineProperty(HTMLCanvasElement.prototype, 'toDataURL', {
value: function () { return 'new valu' }
});
If I didn't redefine toString
it will return code itself when call toString
.如果我没有重新定义
toString
它会在调用toString
时返回代码本身。
HTMLCanvasElement.prototype.toDataURL
does not have an own property toString
by default. HTMLCanvasElement.prototype.toDataURL
默认没有自己的属性toString
。 The toString
method you get by referencing HTMLCanvasElement.prototype.toDataURL.toString
is prototypally inherited from Function.prototype.toString
:您通过引用
HTMLCanvasElement.prototype.toDataURL.toString
获得的toString
方法原型继承自Function.prototype.toString
:
console.log( HTMLCanvasElement.prototype.toDataURL.toString === Function.prototype.toString );
No property exists directly on HTMLCanvasElement.prototype.toDataURL.toString
. HTMLCanvasElement.prototype.toDataURL.toString
上没有直接存在的属性。 But if you add one yourself, via但是如果你自己添加一个,通过
Object.defineProperty(HTMLCanvasElement.prototype.toDataURL, 'toString',
then it will have such an own property, and will also log a property descriptor if you examine it.那么它都会有这样的自有物业,也将记录一个属性描述符,如果你检查它。
If you want to monkeypatch your custom toString
method while keeping HTMLCanvasElement.prototype.toDataURL.toString
empty, you can overwrite Function.prototype.toString
.如果你想在保持
HTMLCanvasElement.prototype.toDataURL.toString
空的同时修补你的自定义toString
方法,你可以覆盖Function.prototype.toString
。
Note that while this is technically possible, it's also very strange to do, and a bad idea to mutate built-in prototypes:请注意,虽然这在技术上是可行的,但这样做也很奇怪,并且改变内置原型是一个坏主意:
const origToString = Function.prototype.toString;
Function.prototype.toString = function() {
if (this === HTMLCanvasElement.prototype.toDataURL) return 'function toDataURL() { [native code] }';
else return origToString.call(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.