Javascript TypeError exception

I have 3 questions. Thank!

First question:

When do JavaScript codes throw a TypeError exception?

Other questions:

I have the codes below:

<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML5 document</title>
<script>
    var str = 'abc'; // str 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>

The method getPrototypeOf()and isPrototypeOf()requires a parameter whose type must be an object. And the type stris a string.

Why does the method getPrototypeOfthrow a TypeError exception and the method isPrototypeOfdoes not raise errors?

If the type stris an object ( var str = new String('abc')), the result Object.prototype.isPrototypeOf(str)is true. But the result is above codes false. Why is it strnot converted from a string to an object automatically when used as a parameter to a method isPrototypeOf?

Thank!

+3
source share
2

.

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. 
0

Source: https://habr.com/ru/post/1789325/


All Articles