2011-02-01 7 views
3

3つの質問があります。ありがとうございました!JavaScriptのTypeError例外に関する質問

最初の質問:

の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です。 isPrototypeOfメソッドのパラメータとして使用すると、strが文字列からオブジェクトに自動的に変換されないのはなぜですか?

ありがとうございました!

+0

文字列コンストラクタ(str = new String( 'abc'))を使用して "str"文字列を作成して、TypeErrorを取得しないようにする必要があります。 –

答えて

0
  1. "TypeError mdc"のための最初のヒットを見てみましょう。それが型エラーをスローするとき、仕様とユーザまでです。

他は特定の質問に答えます。

0

私の理論はisPrototypeOfinstanceofオペレータのような兄弟のようなものなので、彼らは本当に同じ基本的な意味を持つべきです。また、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. 
関連する問題