Reputation:
I'm trying to call the age
, name
and height
together, from only 1 variable called this.anh
from the function called person
.
The way i wrote the list is wrong but what is the right notation? if there is multiple ways, please write them down. :)
<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>
Upvotes: 1
Views: 57
Reputation: 21854
ES5
this.anh = age + ', ' + name + ', ' + height;
ES6 (template literal)
this.anh = `${age}, ${name}, ${height}`;
And instead of creating a new variable, 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"
Upvotes: 1
Reputation: 2923
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)
Since age, name and height are public properties you should use a function for "anh" so that it always returns an up to date value. Otherwise "anh" could get out of sync with the other variables very easily.
Upvotes: 1
Reputation: 10254
You need to concatenate the variables to get your expected output.
this.anh = age + ', ' + name + ', ' + ', ' + height;
Upvotes: 1
Reputation: 65796
You need to add literals where you want them and concatenate the dynamic values.
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)
Upvotes: 2