const Person = function(first='', last='',age=0,gender='男',interests='无'){
this.name = `${first} ${last}`;
this.age = age;
this.gender = gender;
this.interests = interests;
}
Person.prototype.greeting = function(){
console.log(`${this.name} 打招呼 `);
}
const ccg = new Person('cheng','chenggong',20,'男','玩耍');
// ccg.greeting();
console.log(ccg instanceof Person);
const Teacher = function(first,last,age,gender,interests,subject){
Person.call(this,first,last,age,gender,interests);
this.subject = subject;
}
// 将Person原型链上的方法和属性继承过来(通过中间对象,将子类和父类对象分离)
Teacher.prototype = Object.create(Person.prototype);
// 因为原型链继承了Person,所以构造器也是指向了Person,需要将构造器只想Teacher自己本身
Teacher.prototype.constructor = Teacher;
const teacher1 = new Teacher('ccg','',20,'男','玩耍','英语');
teacher1.greeting();
console.log(teacher1);
js中new和Object.create的区别(简单描述):
new 产生的实例,优先获取构造函数上的属性;构造函数上没有对应的属性,才会去原型上查找;如果构造函数中以及原型中都没有对应的属性,就会报错。
Object.create() 产生的对象,只会在原型上进行查找属性,原型上没有对应的属性,就会报错。
网友评论