美文网首页
理解JavaScript的原型与继承

理解JavaScript的原型与继承

作者: 江ls | 来源:发表于2020-12-09 10:50 被阅读0次

Javascript 使用原型来实现类的继承。在ECMAScript6 引入class的概念也是原型继承的语法糖

1. 原型基于构造函数

// 定义Person构造函数
function Person(name, age) {
     // 自有属性
     this.name = name
     this.age = age
}

2. 构造函数自带一个属性prototype,称之“原型”。
prototype也是对象,默认包含constructor属性和 [[proto]]属性

console.log(Person.prototype);
图片20201209100430.png

3. 在原型上添加函数,能被所有Person实例访问,只有一份
(定义在构造函数内的函数在构造多个实例时则有多份)

Person.prototype.sayName = function()   {
      console.log(this.name)
}
console.log(Person.prototype);
图片20201209100736.png

4. new 一个实例
proto 是默认指向其构造函数原型属性的指针
kitty通过proto可以搜索到Person.prototype上定义的属性

let  kitty = new Person('kitty', 10)
console.log(kitty.__proto__ === Person.prototype)  // true

5. 原型链搜索过程:先此对象自身属性上查找,再去它的[[proto]]指向的原型上查找,
如果也没找到,则继续在构造函数的原型(prototype)的[[proto]]上查找,一层层向上查找直到Object.prototype

console.log(Object.prototype.__proto__ === null)  //true

function Person(name, age) {
    let priAttr = 'owner'
    this.name = name
    this.age = age
    this.sayAttr = function() {
        console.log(priAttr)
    }
}
图片20201209102556.png

sayName()添加在Person原型上。 sayAttr()添加在Person构造函数中

6. 借用构造函数+原型链的组合继承方法

function Student(name, age, grade) {
    // 借用构造函数,继承Person的自有属性
    Person.call(this, name, age)
    this.grade = grade
}
// Object.create创建Person.prototype空对象,继承原型上方法
Student.prototype = Object.create(Person.prototype)
// 修改constructor指向
Student.prototype.constructor = Student

let tom = new Student('tom', 11, 4) 
console.log(kitty instanceof Person, tom instanceof Student)
console.log(tom)
图片20201209104906.png

相关文章

网友评论

      本文标题:理解JavaScript的原型与继承

      本文链接:https://www.haomeiwen.com/subject/wtjiwktx.html