1.有的时候我们想要在所有已经存在的对象添加新的属性或方法。

另外,有时候我们想要在对象的构造函数中添加属性或方法。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

使用 prototype 属性就可以给对象的构造函数添加新的属性:

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.nationality = "English";

var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"我父亲对国籍是 " + myFather.nationality; 
</script>

 

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName
};

var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"我对父亲是 " + myFather.name(); 
</script>

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄