js原型和原型链

76 阅读2分钟

class和继承

(1)、constructor 的参数为创建这个类的实例的参数

(2)、属性

(3)、方法

class是面向对象的语法实现,class本质上类似于一个模版,通过模版构建东西。 class实际是个函数,可见是语法糖

class Person {
  constructor(name){
    this.name = name;
  }
  sayHi(){
    console.log(`${this.name} say hi`);
  }
}

class Student extends Person {
  constructor (name, number){
    super(name);
    this.number = number
  }
  getNumber(){
    console.log(`${this.name} number is ${this.number}`)
  }
}

class Teacher extends Person {
  constructor (name, subject){
    super(name);
    this.subject = subject;
  }
  getSubject(){
    console.log(`${this.name} subject is ${this.subject}`);
  }
}
console.log(typeof Person) // 'function'
const xiaoma = new Student('xiaoma', '49');
xiaoma.getNumber();
const laowang = new Teacher('laowang', 'math')
laowang.getSubject()
console.log('xiaoma,,',xiaoma)
console.log('Student,,',Student)
console.log(xiaoma.__proto__)
console.log(Student.prototype)
console.log(xiaoma.__proto__ === Student.prototype); // true

js本身是基于原型继承的语言,es6之前写继承只能依靠原型继承,es6后用class继承,class继承只是一种语法糖,用的还是原型继承不是像java的纯类的继承,现在用es6 class继承

原型和原型链

extends继承 super方法执行父类的构建库constructor

每个class(函数)都有显式原型prototype 原型上有constructor和方法 没有属性

每个实例(对象)都有隐式原型__proto__

每个实例的__proto__指向对应class的prototype

实例基于原型的执行规则,先在实例自身找属性或方法如果没有在去__proto__中找一值沿着__proto__找 即到他的class的prototype中找 再到父组件的prototype中找

// 手写jquery
class JQuery {
  constructor(selector){
    const result = document.querySelectorAll(selector);
    const length = result.length;
    for(let i =0 ;i < length;i++){
      this[i] = result[i]
    }
    this.length = length;
  }
  get(index){
    return this[index]
  }
  each(fn){
    for(let i=0; i<this.length;i++){
      fn(this[i])
    }
  }
  on(type, fn){
     this.each((ele)=>{
       ele.addEventListener(type, fn, false)
     })
  }
}
// 拓展JQuery 插件的形式
JQuery.prototype.dialog = (info)=>{
  console.log('dialog,,,', info);
}

//拓展JQuery 造轮子

class MyJQuery extends JQuery {
  constructor(selector){
    super(selector)
  }
  dialog(info){
    console.log('dialog,,,', info);
  }
}

window.JQuery = JQuery
window.MyJQuery = MyJQuery

instanceOf

instanceOf 通过对象的隐式原型去 找 类的显式原型 如果能对上就是 true

wanglaoshi instanceof People
true
wanglaoshi instanceof Teacher
true
wanglaoshi instanceof Object
true
wanglaoshi instanceof Array
false


let a = new Number(2)
undefined
a instanceof Number
true
let b = 1
undefined
b instanceof Number
false

[] instanceof Array
true
[] instanceof Object
true

null instanceof Object
false

所有的引用类型都继承自Object

Object.prototype.toString.call 可以判断所有的数据类型

Object.prototype.toString.call(123) "[object Number]"

new Object()

new Object()等同于{} 原型Object.prototype

Object.create()

Object.create(null) 没有原型 Object.create({...})指定原型