2017-07-05 8 views
1
<html> 
    <head> 
    <script> 
     function User(name,age){ 
     this.name=name; 
     this.age=age; 
     } 
     var user = new User('Daniel', 45); 
     document.write(user[name]+' '+'is'+' '); //line 1 
     document.write(user[age]+' '+'years old!'); // line 2 
    </script> 
    </head> 
    <body> 

    </body> 
</html> 

属性、 は、私は年齢のために出力 として、i「は未定義」しまった名前の場合、オブジェクトのユーザー のプロパティにアクセスしようとしたとき、私はその年齢がすることができません を定義されていないというエラーを得ました私はなぜ2行目のエラーが発生しているのか理解しています。 と1行目の '未定義'の値です。どちらも同じエラーが発生しますか? ここに私の疑いを明確にしてください。アクセスオブジェクトは、上記のコードでは

答えて

0

文字列として名前と年齢を指定する必要があります。それがこのuser['name']

<html> 
 
      <head> 
 
       <script> 
 
        function User(name,age){ 
 
         this.name=name; 
 
         this.age=age; 
 
        } 
 
        var user = new User('Daniel', 45); 
 
        document.write(user["name"]+' '+'is'+' '); //line 1 
 
        document.write(user["age"]+' '+'years old!'); // line 2 
 
       </script> 
 
      </head> 
 
      <body> 
 

 
      </body> 
 
     </html>

あるいは単に使うようにする必要があります。表記

<html> 
 
      <head> 
 
       <script> 
 
        function User(name,age){ 
 
         this.name=name; 
 
         this.age=age; 
 
        } 
 
        var user = new User('Daniel', 45); 
 
        document.write(user.name+' '+'is'+' '); //line 1 
 
        document.write(user.age+' '+'years old!'); // line 2 
 
       </script> 
 
      </head> 
 
      <body> 
 

 
      </body> 
 
     </html>

0

ウィンドウオブジェクトのプロパティがありますnameという名前です。
それは何なのか分かりません。 ウィンドウ名が設定されていなかったので、だから、[EDIT] the name of the window is used primarily for setting targets for hyperlinks and forms.
それはそれはあなたがライン2
user[name]に入ると、あなたが定義されていないエラーを取得しない定義されているためで、user['']である、user[window.name]と等価です。

+0

ありがとうございました – Chinmaya

関連する問題