gpt4 book ai didi

JavaScript: "TypeError: Illegal invocation"但我没有调用任何函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:48:53 26 4
gpt4 key购买 nike

注意:我已经搜索过这个错误,但我发现的所有内容都是关于调用函数的。我没有调用任何函数。我只是想访问一个属性。


当我执行这段简单的代码时出现错误:

var a = document.getElementById("something");
var b = Object.create(a);
console.log(b.baseURI) //Throws error with any property of a
<p id="something">Hi! I exist just for demo purposes. This error can occur with any element.</p>

我不知道为什么会这样。如果我尝试从 b...

的原型(prototype)中获取属性,代码工作正常
var a = document.getElementById("something");
var b = Object.create(a);
console.log( Object.getPrototypeOf(b.baseURI) ) //Works

...并且还使用普通对象。

var a = {foo: "Foo!"};
var b = Object.create(a);
console.log(b.foo) //Works

为什么会这样?对我来说完全是无稽之谈。 MDN说:

When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

b(在第一个例子中)的原型(prototype)链是:

HTMLParagraphElement --> HTMLParagraphElement (the actual element object) --> HTMLParagraphElement --> HTMLElement --> Element --> Node --> EventTarget --> Object --> null

( Proof )

编辑:请注意原型(prototype)链中的第一个st 对象是一个HTMLParagraphElement。这是正常的,所以这不是问题所在。 ( Image )

问题(我认为)是属性被复制到主要的 b 对象,而不仅仅是复制到 b 的原型(prototype)。这意味着浏览器在第一个对象中找到了一个匹配的名称并尝试访问它,但它抛出了一个错误。 ( Image ;单击 (...) 会导致错误)。

但是,我仍然不明白为什么会发生这种情况,也不明白为什么会抛出错误。

最佳答案

此行为是由 specification 的实现引起的.这些 DOM 节点是所谓的“平台对象”,它们实现 getter 的方式与“普通”javascript 略有不同。

简而言之:如果没有额外的工作,它们就无法扩展。

var a = document.getElementById("something");
var b = Object.create(a);

当访问bbaseURI时,它的this指向的b不是一个有效的'平台对象'。这会导致 Illegal invocation 错误。通过 prototype 访问它确实有效,因为它的 this 指向 prototype 这是一个有效的“平台对象”。

这个关于 Chrome 问题的评论更详细地解释了它,如果你真的需要它,还提供了一个解决方法:https://bugs.chromium.org/p/chromium/issues/detail?id=495437#c7

关于JavaScript: "TypeError: Illegal invocation"但我没有调用任何函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com