前端面试 js的几种继承
原型继承
function Father(name){
this.name = name;
this.getName = function(){
console.log(this.name);
};
};
Father.prototype.show = function(){
console.log(this.name);
};
Father.prototype.age = 18;
function Son(name){
this.name = name;
};
Son.prototype = new Father();
let s = new Son("lbj");
s.show();
s.getName();
构造函数继承
function Father(...args) {
this.name = "lbj";
this.getName = function () {
console.log(this.name);
};
};
Father.prototype.show = function () {
console.log(this.name);
};
Father.prototype.age = 18;
function Son(...args){
Father.call(this,...args);
};
let s = new Son(1,5,6);
s.getName();
s.show();
组合继承
function Father(...args) {
this.name = "lbj";
this.getName = function () {
console.log(this.name);
};
};
Father.prototype.show = function () {
console.log(this.name);
};
Father.prototype.age = 18;
function Son(...args){
Father.call(this,args);
};
Son.prototype = new Father();
寄生组合继承
function Father(...args) {
this.name = "lbj";
this.getName = function () {
console.log(this.name);
};
};
Father.prototype.show = function () {
console.log(this.name);
};
function Son() {
Father.call(this);
};
Son.prototype = Object.create(Father.prototype);
Object.defineProperty(Son.prototype, "constructor", {
value: Son,
enumerable: false
})
function object(o) {
function F() { };
F.prototype = o;
return new F();
}
class继承
class Father{};
class Son extends Father{
constructor(...args){
super(...args);
};
};
|