构造一个函数及其变量

时间:2016-11-22 01:23:22

标签: javascript function

我正试图从名为age的函数中仅调用名为name的1个变量,同时调用heightthis.anhperson。 我写这个清单的方式是错的,但正确的符号是什么?如果有多种方式,请写下来。 :)

<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>

4 个答案:

答案 0 :(得分:3)

您需要在需要的位置添加文字并连接动态值。

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

<强> ES5

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

ES6 template 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"    

答案 2 :(得分:2)

您需要连接变量以获得预期的输出。

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

答案 3 :(得分:1)

&#13;
&#13;
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)
&#13;
&#13;
&#13;

由于年龄,姓名和身高都属于公共属性,因此您应该使用&#34; anh&#34;所以它总是返回一个最新的值。否则&#34; anh&#34;可能很容易与其他变量不同步。