javascript - 关于JavaScript的TypeError异常的一个问题

标签 javascript type-conversion typeerror

我有 3 个问题。谢谢!

第一个问题:

JavaScript 代码什么时候会引发“TypeError”异常?

其他问题:

我有以下代码:

<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML5 document</title>
<script>
    var str = 'abc'; // str's type is string, not object

    // Syntax: Object.getPrototypeOf(object)
    alert(Object.getPrototypeOf(str)); // Uncaught TypeError: Object.getPrototypeOf called on non-object

    // Syntax: prototype.isPrototypeOf(object)
    if (Object.prototype.isPrototypeOf(str)) { // false
        alert('true');
    } else {
        alert('false');
    }
</script>

方法 getPrototypeOf()isPrototypeOf() 都需要一个参数,类型应该是对象。而str的类型是string。

为什么getPrototypeOf方法会抛出TypeError异常,而isPrototypeOf方法不会抛出任何错误?

如果 str 的类型是对象 (var str = new String('abc')),则 Object.prototype.isPrototypeOf(str )true。但是上面代码的结果是false。为什么 str 用作 isPrototypeOf 方法的参数时,没有自动从字符串转换为对象?

谢谢!

最佳答案

  1. 查看 "TypeError mdc" 的第一个匹配项.当它抛出类型错误时,取决于规范和用户。

另一个回答具体问题。

关于javascript - 关于JavaScript的TypeError异常的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4866940/

相关文章:

python-3.x - TypeError:目标函数非线性优化 Gekko 中类型 'int' 的对象没有 len()

python - TypeError 'x' 对象没有属性 '__getitem__'

javascript - 去掉一个数中的小数

javascript - 如何访问conditionizr对象?

javascript - jQuery 数据表 : Combining column visibility with individual column filters (text inputs)?

c++ - 使用简单类型说明符的显式类型转换(功能符号)

javascript - 将 css rtl 定向格式复制到剪贴板

java - Spring MVC 转换方法

.NET 实现 : Double conversion in Math. Min(float, float)

python - Python 错误 : missing 1 required positional argument