简体   繁体   English

扩展javascript文字对象

[英]Extending javascript literal object

Why JohnDoe.whoAreYou() does return undefined ?: 为什么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>

Because you aren't returning anything from this function. 因为您没有从此函数返回任何内容。 Try like this: 尝试这样:

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

Your approach to creating objects is very limiting. 您创建对象的方法非常有限。

You should rather create a new instance from a constructor and pass in the values to that function. 您应该从构造函数创建一个新实例,然后将值传递给该函数。

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