js 面向对象精要——继承
2019-6-9
原型对象链和 Object.protytype
继承 在面向对象语言中,子类从父类中继承父类的属性和方法,叫继承
JavaScript内置的继承方法被称为原型对象链。
原型对象链:对象继承其原型对象,原型对象继承它的原型对象
所有的对象自动继承 Object.prototype,除非自定义指定
eg:
var book = {
title: 'JavaScript'
}
var prototype = Object.getPrototypeOf(book)
console.log(prototype === Object.prototype) // true
继承自 Object.prototype 的方法
- hasOwnPrototype() 检查是否存在一个给定名字的自有属性
- prototypeIsEnumerable() 检查一个自有属性是否可枚举
- isPrototypeOf() 检查一个对象是否是另一个对象的原型对象
- valueOf() 返回一个对象的值表达式
- toString() 返回一个对象的字符串表达式 eg: [object object]
对象继承
指定哪个对象时新对象的 [[Prototype]] (原型)
对象字面形式会隐式指定 Object.prototype 为其 [[Prototype]] 原理也是调用了 Object.create() 方法
也可以用 Object.create() 显示指定
var person1 = {
name: 'Tom',
sayName: function() {
console.log(this.name)
}
}
var person2 = Object.create(person1, {
name: {
configurable: true,
enumerable: true,
value: 'Li',
writable: true
}
})
person1.sayName() // 'Tom'
person2.sayName() // 'Li'
console.log(person1.isPrototypeOf(person2)) // true
console.log(person2.hasOwnPrototype('sayName')) // false
console.log(person1.hasOwnPrototype('sayName')) // true
构造函数继承
几乎所有函数都有 prototype 属性,它可以配修改或替换,
构造函数有个一 constructor 属性
var YourConstructor() {
//initialization
}
YourConstructor.prototype = Object.create(Object.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: YourConstructor, // 指向函数本身
writable: true
}
})
构造函数窃取
构造函数继承父类的方法
function SuperClass(name) {
this.name = name
}
SuperClass.ptototype.getName = function() {
console.log(this.name)
}
function SubClass(name, title) {
// 改变this指向,把父类中的 this 改为了子类中的 this
SuperClass.call(this, name)
// 子类新增的属性
this.title = title
}
// 类式继承,继承父类,原型指向父类的一个实例
SubClass.prototype = new SuperClass()
// 子类新增的方法
Subclass.prototype.getTime = function() {}