A question about JavaScript's TypeError exception
I've 3 questions. Thank you!
First question:
When will JavaScript codes cause a "TypeError" exception?
Other questions:
I've codes below:
<!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>
Method getPrototypeOf()
and isPrototypeOf()
are both need a parameter which type should be object. And str
's type is string.
Why getPrototypeOf
method throws an TypeError exception, and isPrototypeOf
method doesn't throws any errors?
If str
's type is object (var str = new String('abc')
), the result of Object.prototype.isPrototypeOf(str)
is true
. But the result of codes above is false
. Why isn't str
converted from s开发者_运维技巧tring to object automatically when it's used as a parameter of isPrototypeOf
method?
Thank you!
- Take a look at the first hit for "TypeError mdc". When it throws a typeerror is upto the specification and the user.
The other answeres the specific question.
My theory is that isPrototypeOf
is kind of like the brother to the instanceof
operator so they really should have the same basic semantics. Also new functions in ECMAScript 5 tend to be a bit more strict when compared to functions in older editions. Here are the algorithms used.
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.
精彩评论