原型链
原型对象
构造函数初始化的时候,会创造一个特殊的实例化对象,该对象为原型对象,构造函数的prototype属性指向原型对象
原型链
当实例化调用属性和方法的时候,会在实例化本身找,如果没有就沿着__proto__属性找到原型对象的__proto__属性,找原型对象上的属性和方法(如果找到就用),如果没有就一直往上走,直到找到Object 原型对象的__proto__属性为null为止,这一系列由__proto__属性串连起来的原型对象为原型链。
①所有引用类型都有一个__proto__(隐式原型)属性,属性值是一个普通的对象
②所有函数都有一个prototype(原型)属性,属性值是一个普通的对象
③所有引用类型的__proto__属性指向它构造函数的prototype
链接: https://blog.csdn.net/xiaoermingn/article/details/80745117.
ES5继承
function Parent(name, age) {
this.name = name;
this.age = age;
}
Parent.prototype.run = function() {
console.log('run')
}
function Child(name, age, grade) {
// Parent.call(this, name, age)
Parent.apply(this, [name, age])
this.grade = grade;
}
Child.prototype = new Parent(); //Child的proto指向Partent的proto上有run()
// Child.prototype = new Parent("内部",4);
Child.prototype.study = function() {
console.log('study');
}
let c1 = new Child('Alice', 10, '五');
console.log(c1);
ES6继承
类(class)是在 JS 中编写构造函数的新方法。它是使用构造函数的语法糖,在底层中使用仍然是原型和基于原型的继承。
class Parent{
constructor(name,age){
this.name=name
this.age=age
}
say(){
console.log("say");
}
}
// 继承
class Child extends Parent{
constructor(name,age,grade){
super(name,age)
this.grade=grade
}
study(){
console.log("study");
}
}
let c1 = new Child("mary",5,1)
console.log(c1);