采用一下的call的这种方式,会使得引用数据类型不受多个new 的相互影响。
function Person(name){
this.name = name;
//引用的数据类型
this.Colors = ["red","yellow"];
}
function Student(age){
//用call继承,还能传递参数name值
Person.call(this,"huang");
this.age = age;
}
//原型继承
Student.prototype = new Person(); //(1)
//由于上行的继承,使得Student.prototype.constructor = Person
//这行将它改为指向自身,Student.prototype.constructor = Student
Student.prototype.constructor = Student; //(2)
//经过(1)(2)后才能写自身的函数,否则,没有将constuctor转换过来,会出现错误
Student.prototype.sayAge = function(){
console.log("hllo") ;
}
var stu1 = new Student(21);
stu1.Colors.push("black");
console.log(stu1.Colors);
var stu2 = new Student(23);
console.log(stu2.Colors);
// console.log(stu.sayName());
// console.log(stu.age);
Student.prototype.sayAge();