Class的使用:
// 父類 class People { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } // 子類 class Student extends People { constructor(name, number) { super(name);//super使用父類幫忙定義this.name this.number = number } sayHi() { console.log(`姓名:${this.name},學號:${this.number}`) } } const a = new Student('aaa',123) a.sayHi() a.eat()View Code
型別判斷-instance:
// 父類 class People { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } // 子類 class Student extends People { constructor(name, number) { super(name);//super使用父類幫忙定義this.name this.number = number } sayHi() { console.log(`姓名:${this.name},學號:${this.number}`) } } const a = new Student('aaa',123) // a instanceof Student // true // a instanceof People // true // a instanceof Object // true // [] instanceof Array // true // [] instanceof Object // true // {} instanceof Object // trueView Code
原型:
// 父類 class People { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } // 子類 class Student extends People { constructor(name, number) { super(name);//super使用父類幫忙定義this.name this.number = number } sayHi() { console.log(`姓名:${this.name},學號:${this.number}`) } } const a = new Student('aaa',123) // class 實際上是函式,是語法糖 // typeof People // 'function' // typeof Student // 'function' // 隱式原型和顯式原型 console.log( a ) console.log( a.__proto__ ) console.log( Student.prototype ) console.log( a.__proto__ === Student.prototype ) // 原型關系 // 每個class都有顯式原型 prototype // 每個實體都有隱式原型 __proto__ // 實體的__proto__指向對應class的prototype // 基于原型的執行規則 // 先在自身屬性和方法尋找 // 如果找不到自動去__proto__尋找View Code
原型鏈:
// 父類 class People { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } // 子類 class Student extends People { constructor(name, number) { super(name);//super使用父類幫忙定義this.name this.number = number this.rank = () => { console.log('rank 10') } } sayHi() { console.log(`姓名:${this.name},學號:${this.number}`) } } const a = new Student('aaa', 123) console.log(a); console.log(Student.__proto__.prototype); console.log(People.prototype); console.log(Student.__proto__.prototype === People.prototype); // true // hasOwnProperty() 方法來驗證是否該物件自己的 console.log(a.hasOwnProperty('name')); console.log(a.hasOwnProperty('sayHi')); console.log(a.hasOwnProperty('rank')); // 原型鏈直至找到Object的__proto__為止,Object的__proto__為null // instanceof的原理是原型鏈查找模式,一步步對照Class的顯式原型是否存在View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/11186.html
標籤:JavaScript
上一篇:前端面試題整理——深拷貝
