ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

js之继承

2026/9/18 22:36:42 拓冰建站 浏览量
js之继承

js之继承

      • 1、原型 prototype 和 __proto__
      • 2、原型链
      • 3、继承
      • 4、hasOwnProperty

1、原型 prototype 和 proto

  • 每个对象都有一个__proto__属性,并且指向它的prototype原型对象
  • 每个构造函数都有一个prototype原型对象
  • prototype原型对象里的constructor指向构造函数本身
    在这里插入图片描述
    作用:实例对象的__proto__指向构造函数的prototype,从而实现继承。prototype对象相当于特定类型所有实例对象都可以访问的公共容器
    在这里插入图片描述

示例

function Person(nick, age){this.nick = nick;this.age = age;
}
Person.prototype.sayName = function(){console.log(this.nick);
}var p1 = new Person('Byron', 20);var p2 = new Person('Casper', 25);p1.sayName()  // Byronp2.sayName()  // Casperp1.__proto__ === Person.prototype       //truep2.__proto__ === Person.prototype   //truep1.__proto__ === p2.__proto__           //truePerson.prototype.constructor === Person  //true

2、原型链

在这里插入图片描述

arr.__proto__ === Array.prototype
true
Array.prototype.__proto__ === Object.prototype
true
arr.__proto__.__proto__ === Object.prototype
true// 原型链的终点
Object.prototype.__proto__ === null
true

原型链如下:

arr ---> Array.prototype ---> Object.prototype ---> null

这就是传说中的原型链,层层向上查找,最后还没有就返回undefined

3、继承

继承是指一个对象直接使用另外一个对象的属性方法

function Person (name, age) {this.name = namethis.age = age
}// 方法定义在构造函数的原型上
Person.prototype.getName = function () { console.log(this.name)}

定义Teacher构造函数

function Teacher (name, age, subject) {Person.call(this, name, age)this.subject = subject
}

原理

Teacher.prototype = Object.create(Person.prototype)Teacher.prototype.constructor
ƒ Person(name, age) {this.name = namethis.age = age
}---Teacher.prototype.constructor = Teacher
ƒ Teacher(name, age, subject) {Person.call(this, name, age)this.subject = subject
}

继承方法的最终方案

Teacher.prototype = Object.create(Person.prototype)
Teacher.prototype.constructor = Teacher

4、hasOwnProperty

在原型链上查询属性比较耗时,对性能有影响,试图访问不存在的属性时会遍历整个原型链。
遍历对象属性时,每个可枚举的属性都会被枚举出来。 要检查是否具有自己定义的属性,而不是原型链上的属性,必须使用hasOwnProperty方法。
hasOwnProperty 是 JavaScript 中唯一处理属性并且不会遍历原型链的方法。