面试题答案
一键面试1. 代码作用解释
Object.create(Person.prototype)
:- 这行代码创建了一个新的对象,这个新对象的原型被设置为
Person.prototype
。这使得Student
实例能够继承Person
原型对象上定义的属性和方法。通过这种方式,Student
实现了对Person
的原型继承,例如sayHello
方法。这样做避免了直接使用Student.prototype = Person.prototype
,因为如果直接赋值,会导致Student
和Person
的原型对象完全共享,修改一方会影响另一方。使用Object.create
创建一个新对象作为Student
的原型,使得Student
有自己独立的原型对象,同时又能继承Person
原型的属性和方法。
- 这行代码创建了一个新的对象,这个新对象的原型被设置为
Student.prototype.constructor = Student
:- 当使用
Object.create(Person.prototype)
创建Student.prototype
时,新的原型对象的constructor
属性指向的是Person
(因为它继承自Person.prototype
)。而我们希望Student
实例的constructor
属性指向Student
自身,这样通过instanceof
操作符以及其他需要判断构造函数的场景下能得到正确的结果。例如,如果没有这行代码,s instanceof Student
虽然会返回true
,但Student.prototype.constructor
指向的却是Person
,这可能会引起混淆。通过手动设置Student.prototype.constructor = Student
,确保了Student
实例的constructor
属性正确指向Student
。
- 当使用
2. sayHello
方法查找过程
- 当调用
s.sayHello()
时,JavaScript引擎首先在Student
实例s
自身的属性中查找sayHello
方法。由于Student
构造函数中没有直接定义sayHello
方法,所以在实例上找不到。 - 然后,JavaScript引擎会沿着原型链向上查找。
Student
实例的原型是通过Object.create(Person.prototype)
创建的,所以它的原型对象(Student.prototype
)上也没有sayHello
方法。 - 接着,继续沿着原型链向上,
Student.prototype
的原型是Person.prototype
,在Person.prototype
中找到了sayHello
方法,于是JavaScript引擎调用该方法,并将this
绑定到Student
实例s
上,最终输出Hello, I'm John
。