关于JavaScript的TypeError异常的问题

时间:2011-02-01 19:15:04

标签: 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的类型是字符串。

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

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

谢谢!

2 个答案:

答案 0 :(得分:0)

我的理论是isPrototypeOf有点像instanceof运算符的兄弟,因此它们应该具有相同的基本语义。与旧版本中的功能相比,ECMAScript 5中的新功能往往更加严格。以下是使用的算法。

15.2.3.2  Object.getPrototypeOf ( O ) 

When the getPrototypeOf function is called with argument O, 
the following steps are taken: 

1.  If Type(O) is not Object throw a TypeError exception. 
2.  Return the value of the [[Prototype]] internal property of O. 

15.2.4.6  Object.prototype.isPrototypeOf (V) 

When the isPrototypeOf method is called with argument V, 
the following steps are taken: 

1.  If V is not an object, return false. 
2.  Let O be the result of calling ToObject passing the this value as 
    the argument.  
3.  Repeat 
  a.  Let V be the value of the [[Prototype]] internal property of V. 
  b.  if V is null, return false 
  c.  If O and V refer to the same object, return true. 

答案 1 :(得分:0)

  1. 看看"TypeError mdc"的第一个点击。当它抛出一个类型错误是由规范和用户决定的。
  2. 另一个回答了具体问题。