FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

已知函数 A,要求构造⼀个函数 B 继承 A

Open lgwebdream opened this issue 5 years ago • 3 comments

function A(name) {
  this.name = name;
}
A.prototype.getName = function () {
  console.log(this.name);
};

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

// 一: 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);

GolderBrother avatar Aug 30 '20 13:08 GolderBrother

  //已知函数 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()

Alicca-miao avatar Sep 29 '24 09:09 Alicca-miao