2011-02-01 61 views
3

我有3个问题。谢谢!关于JavaScript的TypeError异常的问题

第一个问题:

的JavaScript代码的时候会引起 “类型错误” 异常?

其他问题:下面

我有代码:

<!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方法的参数时,会自动从字符串转换为对象?

谢谢!

+0

你应该通过String构造函数构造你的“str”字符串(str = new String('abc')),这样你就不会得到TypeError.I同意了..这有点奇怪 – 2011-02-01 19:28:23

回答

0
  1. 看看先打了"TypeError mdc"。当它抛出一个typeerror时,就取决于规范和用户。

另一个回答具体问题。

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.