2013-02-28 110 views
1

我正在嘗試創建一個Person類。該人的年齡將是一個隨機數,由if/else語句確定。現在它似乎只在將函數放置在對象之外或作爲單獨的鍵時才起作用。如何在對象鍵中放置一個if/else語句?

function age(x) { 
    if (x.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) { 
     return Math.floor(Math.random()*40+1); 
    } 
    else { 
     return Math.floor(Math.random()*40+41); 
    } 
} 

function person(name) { 
    this.name = name; 
    this.age = age(name); 
} 

var people = { 
    joe: new person("Joe") 
}; 

console.log(people.joe.age); 
\\ returns a number 41-80 

有沒有辦法讓我直接把功能進入「this.age」鍵,並有同樣的事情發生,就像這樣:

function person(name) { 
    this.name = name; 
    this.age = function age() { 
     if (this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) { 
      return Math.floor(Math.random()*40+1); 
     } 
     else { 
      return Math.floor(Math.random()*40+41); 
     } 
}; 

回答

5

您可以立即執行的功能:

function person(name) { 
    this.name = name; 
    this.age = (function age() { 
     if (this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) { 
      return Math.floor(Math.random()*40+1); 
     } 
     else { 
      return Math.floor(Math.random()*40+41); 
     } 
    })(); 
}; 
4
function person(name) { 
    this.name = name; 
    this.age = (function age() { 
     var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0))?1:41; 
     return Math.floor(Math.random()*40+x); 
     })(); 
}; 

(function(){})()你」重新執行它。

(function(){}) //this converts the function into a statement 
() // this executes 
+0

謝謝,通過將函數轉換爲語句並立即執行它學到了一些新東西。 – Korey 2013-02-28 23:17:14

+0

所以...它的工作? – martriay 2013-02-28 23:19:49

+0

是的,它的工作。謝謝。 – Korey 2013-02-28 23:23:05

2

你必須定義封閉(功能)和右側上執行它。

function person(name) { 
     this.name = name; 
     this.age = (function age() { 
      var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) ? 1 : 41; 
       return Math.floor(Math.random()*40+x); 
      })(); 
    };