2016-11-22 76 views
1

我想打電話給agenameheight在一起,從只有1名爲this.anh從名爲person函數變量。 我寫清單的方式是錯誤的,但是正確的符號是什麼?如果有多種方式,請寫下來。 :)構建功能和它的變量

<script type="text/javascript"> 

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

var koolz = new person(20,"koolz",200); 



document.write(koolz.anh) 

</script> 
+1

預期的結果是什麼? '「20,koolz,200」'? –

+0

是的!那就對了! @EliasSoares – KOOLz

回答

2

ES5

this.anh = age + ', ' + name + ', ' + height; 

ES6template literal

this.anh = `${age}, ${name}, ${height}`; 

,而不是創建一個新的變量,並you can override the toString method

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

person.prototype.toString = function() { 
    return this.age + ', ' + this.name + ', ' + this.height; 
} 

var koolz = new person(20, 'koolz', 200); 

koolz.toString() // "20, koolz, 200"  
3

您需要在需要的位置添加文字並連接動態值。

function person(age, name, height){ 
 
    this.age = age; 
 
    this.name = name; 
 
    this.height = height; 
 

 
    // If you want a literal comma and space to separate the values 
 
    // then you need to concatenate them to the variables. 
 
    this.anh = age + ", " + name + ", " + height; 
 

 
    // Or, if the data were in an array, like this: 
 
    var arry = [this.age, this.name, this.height ]; 
 
    
 
    // You could concatenate them like this: 
 
    var result = arry.join(", "); 
 
    console.log(result); 
 
} 
 

 
var koolz = new person(20,"koolz",200); 
 
document.write(koolz.anh)

2

您需要連接的變量,讓你期望的輸出。

this.anh = age + ', ' + name + ', ' + ', ' + height; 
1

function person(age, name, height) { 
 
    this.age = age; 
 
    this.name = name; 
 
    this.height = height; 
 
    this.anh = function() { 
 
    return this.age + ", " + this.name + ", " + this.height; 
 
    }; 
 
    this.anh2 = age + ", " + name + ", " + height; 
 
} 
 

 
var koolz = new person(20, "koolz", 200); 
 
console.log(koolz.anh()) 
 
console.log(koolz.anh2) 
 

 
koolz.age = 25; 
 
koolz.height = 210; 
 

 
console.log("This has the updated values.") 
 
console.log(koolz.anh()) 
 

 
console.log("Other way doesn't ever change") 
 
console.log(koolz.anh2)

由於年齡,姓名和高度公共屬性,你應該使用功能「無水」,所以它總是返回一個最新的值。否則,「anh」可能很容易與其他變量不同步。