2010-11-22 64 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