function Person(name, age) {
this.name = name
this.age = age
}
function Student(subject) {
this.subject = "语文"
}
function Person(name, age) {
this.name = name
this.age = age
Student.call(this, name, age)
}
var person1 = new Person("张三", "18")
console.log(person1.subject) // 语文
Person.prototype = new Student()
// 等于覆盖或者删除了原先的 prototype 对象的值,然后给予一个新值。
Person.prototype.constructor = Person;
// 任何一个 prototype 对象都具有一个 constructor 属性,指向它的构造函数。
// 如果不加这下一行代码,Person.prototype.constructor 会指向 Student
var person1 = new Student("张三","18");
alert(person1.constructor == Person.prototype.constructor); // true
// 因此在运行 Person.prototype = new Student() ,person1.constructor 也指向 constructor
// 所以因该手动修改 constructor 的指向
// 总代码
function Person(name, age) {
this.name = name
this.age = age
}
function Student(subject) {
this.subject = "语文"
}
Person.prototype = new Student()
Person.prototype.constructor = Person;
var person1 = new Student("张三","18");
console.log(person1.subject) // 语文
function Student(){}
Student.prototype.project = "语文"
Person.prototype = Student.prototype
Person.prototype.constructor = Person;
var person1 = new Student("张三","18");
console.log(person1.subject) // 语文
Person.prototype.constructor = Person;
// 这一行代码直接把 Student.prototype.constructor 的指向给改了(Person)
var middle = function(){}
middle.prototype = Student.prototype;
Person.prototype = new middle();
Person.prototype.constructor = Person;
console.log(Student.prototype.constructor) // Student
原文:https://www.cnblogs.com/earthZhang/p/12346480.html