2010-11-22 95 views
1

爲什麼JohnDoe.whoAreYou()並返回undefined:擴展JavaScript的文本對象

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

首先,你要這樣:JohnDoe.toString =函數(){返回this.firstName + 「」 + this.lastName} – 2010-11-22 17:28:38

回答

4

因爲不必返回這個函數什麼。試試這樣:

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

謝謝,我太習慣REBOL不需要回報。 – 2010-11-22 18:44:54

1

因爲你忘了return從你所定義的「的toString」功能的價值。

3

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

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

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(); 
+0

呃......如果他在他的「toString」函數中放入了一個「return」關鍵字,它就可以很好地工作......當他將函數作爲屬性引用從他的「JohnDoe」對象中調用時,那麼this將確實參考那個對象 – Pointy 2010-11-22 17:35:21