簡體   English   中英

擴展javascript文字對象

[英]Extending javascript literal object

為什么JohnDoe.whoAreYou()確實返回undefined?:

<html>
<head>
</head>

<body>
  <script>
    var JohnDoe = {
        //public property
        firstName: "John",
        lastName: "Doe",

        //public method
        whoAreYou: function() {
          alert( "I am literal object and my name is " + this.toString());
        },
        whatIsYourAge: function() {
          alert("My age is " + this.Age);
        }               
    };    
  </script>

  <script>
    JohnDoe.Age = 10;
    JohnDoe.toString = function() {this.firstName + " " + this.lastName};
    JohnDoe.whoAreYou();    
    JohnDoe.whatIsYourAge();
  </script>

</body>
</html>

因為您沒有從此函數返回任何內容。 嘗試這樣:

JohnDoe.toString = function() {
    return this.firstName + " " + this.lastName;
};

您創建對象的方法非常有限。

您應該從構造函數創建一個新實例,然后將值傳遞給該函數。

function User(firstName, lastName, age) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.age = age;
   // set name etc here
}

User.prototype.toString = function() {
    // Note the "return" so this function actual returns something
    return this.firstName + " " + this.lastName; 
}
User.prototype.whoAreYou = function() {
    alert( "I am literal object and my name is " + this.toString());
}

var JohnDoe = new User("John", "Doe", 10); 
JohnDoe.whoAreYou();


var someoneElse = new User("Someone", "Else", 15); 
someoneElse.whoAreYou();

因為您忘記了從定義的“ toString”函數return值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM