JavaScript | 原型链与继承

JavaScript中的面向对象

首先看下面的代码:我们应该怎么称呼这个Person?

function Person() {

}

var p1 = new Person();
var p2 = new Person();

在JavaScript中,Person是一个函数,它的prototype属性指向一个对象,这个对象的属性包含了Person的所有属性和方法。

在其他语言的编程范式来看,Person是一个类,这个对象的属性包含了Person的所有属性和方法。

面向对象的特点

面向对象有三大特性:封装、继承、多态。

  • 封装:将对象的属性和方法封装在一个对象中,这样就可以避免对象之间的耦合。
  • 继承:将一个对象的属性和方法复制到另一个对象中,这样就可以让子类继承父类的属性和方法。
  • 多态:不同的对象有不同的表现,这样就可以让对象的表现不依赖于它的类型。

继承的好处:能够将重复的代码抽离到父类中,子类可以直接继承父类,不需要重复定义。

JavaScript原型链

从对象上获取属性,如果对象中没有该属性和方法,则从对象的原型链上获取。

var obj = {
    name: 'obj',
};

obj.__proto__.getName = function() {
    return 'Name is obj';
}

console.log(obj.getName());  // Name is obj
62ea26a22203e

原型链的尽头是Object.prototype,Object.prototype的原型是null。

// 普通object
var obj = {
    name: 'obj',
};

console.log(obj.__proto__); // [Object: null prototype] {}
console.log(obj.__proto__.__proto__.__proto__);  // null
// 字符串
var ss = 'ss'

console.log(ss.__proto__); // [String: null prototype] {}

console.log(ss.__proto__.__proto__) ; // [Object: null prototype] {}

[Object: null prototype] {} 的特殊性,该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型了,而该对象上有很多默认的属性和方法。

62ea289cd1f27

利用JavaScript实现继承

62ea3de23df06

JavaScript原型链继承法

利用上述提到的原型链的原理,可以实现继承。

// 父类: 公共属性和方法
function Person() {
  this.name = "Ricky"
  this.friends = []
}

Person.prototype.eating = function() {
  console.log(this.name + " eating~")
}

// 子类: 特有属性和方法
function Student() {
  this.sno = 111
}

var p = new Person()
Student.prototype = p

Student.prototype.studying = function() {
  console.log(this.name + " studying~")
}


// name/sno
var stu = new Student()

console.log(stu.name) // Ricky
stu.eating() // Ricky eating~

stu.studying() // Ricky studying~

通过原型链实现继承会有一些问题:

  • 我们通过直接打印对象是看不到这个属性的;
  • 这个属性会被多个对象共享,如果这个对象是一个引用类型,那么就会造成问题;
  • 不能给Person传递参数,因为这个对象是一次性创建的(没办法定制化);
// 原型链实现继承的弊端:
// 1.第一个弊端: 打印stu对象, 继承的属性是看不到的
console.log(stu) // [Object: Student prototype] {}

// 2.第二个弊端: 创建出来两个stu的对象
var stu1 = new Student()
var stu2 = new Student()

// 直接修改对象上的属性, 是给本对象添加了一个新属性
stu1.name = "kobe"
console.log(stu2.name) // Ricky

// 获取引用, 修改引用中的值, 会相互影响
stu1.friends.push("kobe")

console.log(stu1.friends) // [kobe]
console.log(stu2.friends) // [kobe]

// 3.第三个弊端: 在前面实现类的过程中都没有传递参数
var stu3 = new Student("lilei", 112)

借用构造函数实现继承

为了解决原型链继承中存在的问题,开发人员提供了一种新的技术: constructor stealing(有很多名称: 借用构造函 数或者称之为经典继承或者称之为伪造对象)

方式:在子类型构造函数的内部调用父类型构造函数,例如call, apply, bind等方法。

强调: 借用构造函数也是有弊端:

  1. 第一个弊端: Person函数至少被调用了两次
  2. 第二个弊端: stu的原型对象上会多出一些属性, 但是这些属性是没有存在的必要
// 父类: 公共属性和方法
function Person(name, age, friends) {
  // this = stu
  this.name = name
  this.age = age
  this.friends = friends
}

Person.prototype.eating = function() {
  console.log(this.name + " eating~")
}

// 子类: 特有属性和方法
function Student(name, age, friends, sno) {
  Person.call(this, name, age, friends)
  // this.name = name
  // this.age = age
  // this.friends = friends
  this.sno = 111
}

var p = new Person()
Student.prototype = p

Student.prototype.studying = function() {
  console.log(this.name + " studying~")
}


// name/sno
var stu = new Student("jame", 18, ["kobe"], 111)

console.log(stu.name)
stu.eating()

stu.studying()


// 原型链实现继承已经解决的弊端
// 1.第一个弊端: 打印stu对象, 继承的属性是看不到的
console.log(stu)

// 2.第二个弊端: 创建出来两个stu的对象
var stu1 = new Student("jame", 18, ["lilei"], 111)
var stu2 = new Student("kobe", 30, ["jame"], 112)

// 但如果直接修改对象上的属性, 是给本对象添加了一个新属性
stu1.name = "kite"
console.log(stu2.name) // kobe

// 获取引用, 修改引用中的值, 会相互影响
stu1.friends.push("lucy")

console.log(stu1.friends)
console.log(stu2.friends)

// // 3.第三个弊端: 在前面实现类的过程中都没有传递参数
// var stu3 = new Student("lilei", 112)

原型类继承

这种继承方法不是通过构造函数来实现的,也能实现重复利用另一个对象的属性方法:

var copy = {
  name: "kobe",
  age: 18,
  friends: ["lilei", "jame"]
}

// Object.setPrototypeOf()方法
function createObject1(obj) {
  var newObj = {}
  Object.setPrototypeOf(newObj, obj)
  return newObj
}
var stu1 = createObject1(copy)
console.log(stu1.__proto__ === copy) // true

// 函数原型赋值方法
function createObject2(obj) {
  funnction F() {}
  F.prototype = obj
  return new F()
}
var stu2 = createObject2(copy)
console.log(stu2.__proto__ === copy) // true

// ECMAScript5中的Object.create()方法
var stu3 = Object.create(copy)
console.log(stu3.__proto__ === copy) // true

寄生式继承

寄生式继承的思路是结合原型类继承和工厂模式的一种方式:即创建一个封装继承过程的函数, 该函数在内部以某种方式来增强对象,最后再将这个对象返回。

var personObj = {
  running: function() {
    console.log("running")
  }
}

function createStudent(name) {
  var stu = Object.create(personObj)
  stu.name = name
  stu.studying = function() {
    console.log("studying~")
  }
  return stu
}

var stuObj1 = createStudent("kobe")
var stuObj2 = createStudent("james")

console.log(stuObj1.name) // kobe
stuObj1.running() // running
stuObj1.studying() // studying~

寄生组合式继承

寄生式继承解决了原型属性继承的问题,但constructor指向的是父类的构造函数,而不是子类的构造函数。

function Person(name, age, friends) {
  this.name = name
  this.age = age
  this.friends = friends
}

Person.prototype.running = function() {
  console.log("running~")
}

Person.prototype.eating = function() {
  console.log("eating~")
}


function Student(name, age, friends, sno, score) {
  Person.call(this, name, age, friends)
  this.sno = sno
  this.score = score
}

Student.prototype.studying = function() {
  console.log("studying~")
}

Student.prototype = Object.create(Person.prototype);

var stu = new Student("Ricky", 18, ["kobe"], 111, 100)
console.log(stu) //  Person {name: "Ricky", age: 18, friends: Array(1), sno: 111, score: 100}
stu.studying() // studying~
stu.running() // running~
stu.eating() // eating~

我们可以利用Object.defineProperty()方法来将constructor指向子类的构造函数:

Object.defineProperty(Student.prototype, "constructor", {
  enumerable: false,
  value: Student,
  writable: true,
  configuable: true
})

console.log(stu) //  Student {name: "Ricky", age: 18, friends: Array(1), sno: 111, score: 100}

实现大量这种组合继承,可以通过实现一个工厂函数来实现:

function inheritPrototype(SubType, SuperType) {
  SubType.prototype = Object.create(SuperType.prototype)
  Object.defineProperty(SubType.prototype, "constructor", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: SubType
  })
}

inheritPrototype(Student, Person)

console.log(stu.constructor.name) // Student