Javascript如何实现继承?
1、构造继承
2、原型继承
3、实例继承
4、拷贝继承
【1】:原型prototype机制
function Parent() {
this.name = 'lle';
}
function Child() {
this.age = 18;
}
// 通过原型链让Child继承Parent
Child.prototype = new Parent();
let demo = new Child();
console.log(demo.name);
【2】:apply()
function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, grade) {
Person.apply(this, arguments);
this.grade = grade;
}
let lle = new Student('lle', '18', '6');
console.log('name: ', lle.name, ',age: ', lle.age, ',grade ', lle.grade
【3】 : call()
function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
let lle = new Student('lle', '18', '6');
console.log('name: ', lle.name, ',age: ', lle.age, ',grade ', lle.grade);
后两种概述: JavaScript 中通过call或者apply用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。简单的说就是改变函数执行的上下文,这是最基本的用法。两个方法基本区别在于传参不同。
call(obj,arg1,arg2,arg3);
call第一个参数传对象,可以是null
。参数以逗号分开进行传值,参数可以是任何类型。apply(obj,[arg1,arg2,arg3]);
apply第一个参数传对象,参数可以是数组或者arguments
对象。