向JavaScript对象构造函数添加属性?

对象构造函数添加属性不同于向普通对象添加属性。如果要添加属性,则必须将其添加到构造函数 本身中,而不是在构造函数外部,而我们可以在常规对象中的任何位置添加。

示例1

在以下示例中,在 普通对象的情况下按原样添加属性 由于这里使用了对象构造函数,因此必须将属性添加到构造函数中(如果未定义), 该属性将作为输出执行,如下所示。

<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   Business.language = "chinese";
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
   document.write(person2.language);
</script>
</body>
</html>

输出结果

undefined

示例2

在下面的示例中,属性“ language ”在构造函数内部声明,因此,我们将获得正常的结果,与 false值不同。

<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
      this.language = "chinese";
   }
var person1 = new Business("Trump", "$28.05billion", "73", "President");
var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
document.write(person2.language);
</script>
</body>
</html>

输出结果

chinese