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);
// 因?yàn)樵玩溊^承了Person,所以構(gòu)造器也是指向了Person免猾,需要將構(gòu)造器只想Teacher自己本身
Teacher.prototype.constructor = Teacher;
const teacher1 = new Teacher('ccg','',20,'男','玩耍','英語');
teacher1.greeting();
console.log(teacher1);
js中new和Object.create的區(qū)別(簡單描述):
new 產(chǎn)生的實(shí)例,優(yōu)先獲取構(gòu)造函數(shù)上的屬性囤热;構(gòu)造函數(shù)上沒有對應(yīng)的屬性猎提,才會去原型上查找;如果構(gòu)造函數(shù)中以及原型中都沒有對應(yīng)的屬性赢乓,就會報(bào)錯忧侧。
Object.create() 產(chǎn)生的對象,只會在原型上進(jìn)行查找屬性牌芋,原型上沒有對應(yīng)的屬性,就會報(bào)錯松逊。