我有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}}不会自动从字符串转换为对象?
谢谢!
答案 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)
另一个回答了具体问题。