/** ES5 通过修改原型链实现继承 */
(function() {
// 1. 创建两个构造函数
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.eat = function (type) {
return `${type} food`;
}
function Human(name, age, work) {
/**
* apply: 调用一个对象的一个方法,用另一个对象替换当前对象。
* 例如:B.apply(A, arguments);即A对象调用B对象的方法。
* call:调用一个对象的一个方法,用另一个对象替换当前对象。
* 例如:B.call(A, args1,args2);即A对象调用B对象的方法。
*
* 两者最大的取别就是: apply 传入一个 arguments, call 是一个一个的传参;
*/
/**
* bind & call: 两者的使用方法一致,
* 取别: call 是立即执行,
* bind() 方法创建一个新的函数,在 bind() 被调用时,
* 这个新函数的 this 被指定为 bind() 的第一个参数,
* 而其余参数将作为新函数的参数,供调用时使用。
*/
// 2. 在 子构造函数中 调用 父构造函数
Animal.call(this, ...[name, age]);
// Animal.apply(this, [name, age]);
this.work = work;
}
/**
* 3. 实现继承,将子类的原型对象 prototype 指向 父类 原型对象,
*/
// 让 Human 这个构造函数的 原型对象 指向 animal 的实例,
// 这样的,实例的 __proto__ 也会被 human 继承;
// Human.prototype = new Animal()
Human.prototype = Object.create(Animal.prototype, {
constructor: {
value: Human,
}
})
Human.prototype.constructor = Human
const codePerson = new Human('阿伟', 27, 'coder')
// console.log(codePerson, codePerson.eat('cooked'));
})();
/** class 继承 */
(function() {
class Animal {
constructor(name, type) {
this.name = name
this.type = type
}
getName() {
return this.name
}
static getType() {
return 'all animal'
}
}
/**
* 1. class 通过 extends 关键字 实现继承
*/
class Human extends Animal {
//
constructor (name, type, work) {
/**
* 2. 子类必须在 constructor 方法中调用 super 方法,此 super 方法表示 父类的 constructor
*
* 此时 super 相当于 Animal.call(this, ...[name, age]);
*
* 注意:
* 在子类的构造函数中,只有调用super之后, 才可以使用this关键字,否则会报错;
* 且super必须在 constructor 的第一行调用
*/
super(name, type)
this.work = work
}
}
const codePerson = new Human('阿伟', '27', 'coder')
console.log(codePerson.getName()) // 阿伟
// 3. Human 会继承 父类的静态方法
console.log(Human.getType()) // all animal
// 4. 可以通过 getprototypeOf() 判断 一个类 是否继承自 另一个类;
console.log(Object.getPrototypeOf(Human) === Animal) // true
})();
class extends实现继承
最新推荐文章于 2024-03-10 21:42:16 发布