2016-11-22 75 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”可能很容易与其他变量不同步。