JavaScript 对象构造函数

141 阅读1分钟
原文链接: www.jc2182.com

将方法添加到构造函数

您的构造函数也可以定义方法:
function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.name = function() {return this.firstName + " " + this.lastName;};
}
您不能像向现有对象添加新方法一样向对象构造函数添加新方法。向对象添加方法必须在构造函数内部完成:
function Person(firstName, lastName, age, eyeColor) {
  this.firstName = firstName;  
  this.lastName = lastName;
  this.age = age;
  this.eyeColor = eyeColor;
  this.changeName = function (name) {
    this.lastName = name;
  };
}
changeName()函数将name的值赋给person的lastName属性。 现在你可以尝试:
myMother.changeName("Doe");