在做了一些测试之后,据我了解,对象的原型和在其定义函数中所做的属性声明是分开的。但是,当构造一个新对象时,构造函数将从定义函数和正在创建的对象的原型中提取属性。
例如,
function Person()
{
this.name = "james";
this.age = "shfifty-five";
}
console.log(Person.prototype.name); // prints "undefined", showing how declaring function Person() and Person.prototype are separate.
Person.prototype.gender = "male";
var human = new Person();
console.log(human.name); // prints "james", showing how the object took properties from declaring function Person().
console.log(human.gender); // prints "male", showing how the object took properties from object prototype Person.prototype.
function Student()
{
this.gpa = 4.00;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
var myStudent = new Student();
console.log(myStudent.name); // prints "james"
console.log(myStudent.gender); // prints "male"
/*from above two lines, inheritance holds even though 1) Person() defining function was not called inside Student() defining function
and 2) Person() defining function declares properties of Person object.*/
console.log(myStudent.gpa); // prints "4"
如您所见,在这种情况下,定义函数 Person 确实改变了其对象的属性。但是仍然没有必要在 Student 的构造函数中调用 Person 函数,因为new Person()
构造函数将从两者Person.prototype
和function Person()
定义函数中提取属性。