Une question sur l'exception TypeError de JavaScript
-
28-10-2019 - |
Question
J'ai 3 questions. Merci!
Première question:
Quand est-ce code JavaScript provoquer une exception "TypeError"?
Autres questions:
J'ai des codes ci-dessous:
<!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>
Méthode getPrototypeOf()
et isPrototypeOf()
sont à la fois besoin d'un paramètre quel type doit être objet. Et le type de str
est une chaîne.
Pourquoi méthode getPrototypeOf
renvoie une exception TypeError et la méthode de isPrototypeOf
ne jette pas d'erreur?
Si le type de str
est objet (var str = new String('abc')
), le résultat de Object.prototype.isPrototypeOf(str)
est true
. Mais le résultat des codes ci-dessus est false
. Pourquoi ne pas str
converti de chaîne pour objet automatiquement quand il est utilisé en tant que paramètre de méthode isPrototypeOf
?
Merci!
La solution
- Jetez un coup d'oeil au premier coup "TypeError mdc" . Quand il jette un TypeError est jusqu'à la spécification et l'utilisateur.
Les autres answeres la question spécifique.
Autres conseils
Ma théorie est que isPrototypeOf
est un peu comme le frère de l'opérateur instanceof
donc ils devraient vraiment avoir la même sémantique de base. En outre de nouvelles fonctions dans ECMAScript 5 ont tendance à être un peu plus stricte par rapport aux fonctions dans les éditions anciennes. Voici les algorithmes utilisés.
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.