JS原型链面试题

题目1

function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
};

var john = new Person('John');
john.sayHello();

请问上述代码的输出结果是什么?

答案1

输出结果是:Hello, John

题目2

function Animal(name) {
  this.name = name;
}

Animal.prototype.eat = function() {
  console.log(this.name + ' is eating.');
};

function Cat(name, color) {
  Animal.call(this, name);
  this.color = color;
}

Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

var fluffy = new Cat('Fluffy', 'white');
fluffy.eat();

请问上述代码的输出结果是什么?

答案2

输出结果是:Fluffy is eating.

题目3

var obj1 = { x: 10 };

var obj2 = Object.create(obj1);

console.log(obj2.x);

请问上述代码的输出结果是什么?

答案3

输出结果是:10

题目4

function Car(make, model) {
  this.make = make;
  this.model = model;
}

Car.prototype.start = function() {
  console.log(this.make + ' ' + this.model + ' is starting.');
};

function ElectricCar(make, model, batteryCapacity) {
  Car.call(this, make, model);
  this.batteryCapacity = batteryCapacity;
}

ElectricCar.prototype = Object.create(Car.prototype);
ElectricCar.prototype.constructor = ElectricCar;

ElectricCar.prototype.start = function() {
  console.log(this.make + ' ' + this.model + ' with ' + this.batteryCapacity + ' battery capacity is starting.');
};

var tesla = new ElectricCar('Tesla', 'Model S', '100kWh');
tesla.start();

请问上述代码的输出结果是什么?

答案4

输出结果是:Tesla Model S with 100kWh battery capacity is starting.

题目5

function Shape() {
  this.color = 'red';
}

Shape.prototype.getColor = function() {
  return this.color;
};

function Circle(radius) {
  this.radius = radius;
}

Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;

var myCircle = new Circle(5);
console.log(myCircle.getColor());

请问上述代码的输出结果是什么?

答案5

输出结果是:red

你可能感兴趣的:(javascript)