简体   繁体   English

Javascript Uncaught TypeError:引用document.createElement时非法调用

[英]Javascript Uncaught TypeError: Illegal invocation when referencing document.createElement

If I can write 如果我能写

var x = window.alert;
x("Hello"); //This works as expected.

Why am I not being able to write the same for document.createElement . 为什么我不能为document.createElement编写相同的document.createElement

var h = document.createElement;
h("div"); //This line throws error 

Uncaught TypeError: Illegal invocation 未捕获的TypeError:非法调用

When you call h , its context this refers to the wrong entry. 当你打电话h ,其上下文this指的是输入错误。 You can fix this by binding it to document . 您可以通过将其绑定到document来解决此问题。

var h = document.createElement.bind(document)

alert can be called as-is, so the scope doesn't change when you alias it. alert可以按原样调用,因此在为它加上别名时范围不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM