FE-Interview
FE-Interview copied to clipboard
已知函数 A,要求构造⼀个函数 B 继承 A
function A(name) {
this.name = name;
}
A.prototype.getName = function () {
console.log(this.name);
};
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。
// 一: ES5版本
function A(name) {
this.name = name;
}
A.prototype.getName = function () {
console.log(this.name);
};
function B(name, age){
A.call(this, name);
this.age = age;
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.getAge = function(){
console.log(this.age);
}
const b = new B('james', 18);
b.getName();
b.getAge();
console.log(b);
// 二: ES6版本
function A(name) {
this.name = name;
}
A.prototype.getName = function () {
console.log(this.name);
};
class B extends A{
constructor(name, age){
super(name);
this.age = age;
}
getAge(){
console.log(this.age);
}
}
const b = new B('james', 18);
b.getName();
b.getAge();
console.log(b);
//已知函数 A,要求构造⼀个函数 B 继承 A
function A(name) {
this.name = name;
}
A.prototype.getName = function () {
console.log(this.name);
};
function B(name,color) {
A.call(this,name)
this.color=color
}
B.prototype=Object.create(A.prototype)
B.prototype.constructor=B
B.prototype.getName=function() {
console.log(`this is ${this.name}+${this.color}`);
}
let aa = new B('hello','bye')
aa.getName()