MST

星途 面试题库

面试题:JavaScript中原型方法与this的基础应用

请解释JavaScript中原型方法是如何实现继承的,并举例说明在构造函数中使用this的作用。同时,描述一下当在原型方法中使用this时,它的指向规则是什么。
47.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

1. JavaScript 中原型方法实现继承的原理

在 JavaScript 中,每个函数都有一个 prototype 属性,这个属性是一个对象,它包含了可以被该函数创建的所有实例共享的属性和方法。当使用构造函数创建一个新对象时,新对象的 __proto__ 属性会指向构造函数的 prototype

继承的实现原理基于原型链。当访问一个对象的属性或方法时,如果对象本身没有该属性或方法,JavaScript 会沿着原型链向上查找,直到找到该属性或方法或者到达原型链的顶端(null)。

例如:

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

Animal.prototype.speak = function() {
    console.log(this.name +'makes a sound.');
};

function Dog(name, breed) {
    Animal.call(this, name);
    this.breed = breed;
}

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

Dog.prototype.bark = function() {
    console.log(this.name +'barks.');
};

const myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak(); // Buddy makes a sound.
myDog.bark(); // Buddy barks.

在上述代码中,Dog 构造函数通过 Object.create(Animal.prototype) 创建了一个新的原型对象,这个原型对象继承自 Animal.prototype。这样 Dog 的实例就可以访问 Animal.prototype 上的方法。

2. 在构造函数中使用 this 的作用

在构造函数中,this 指向新创建的对象实例。构造函数通过 this 来为新对象添加属性和方法。例如:

function Person(name, age) {
    this.name = name;
    this.age = age;

    this.introduce = function() {
        console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
    };
}

const person1 = new Person('Alice', 30);
person1.introduce(); // Hi, I'm Alice and I'm 30 years old.

Person 构造函数中,this.namethis.age 为新创建的 person1 对象添加了 nameage 属性,this.introduceperson1 对象添加了 introduce 方法。

3. 在原型方法中使用 this 的指向规则

在原型方法中,this 指向调用该方法的对象实例。例如:

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

Car.prototype.displayInfo = function() {
    console.log(`This is a ${this.make} ${this.model}.`);
};

const myCar = new Car('Toyota', 'Corolla');
myCar.displayInfo(); // This is a Toyota Corolla.

displayInfo 原型方法中,this 指向 myCar 这个实例对象,所以可以正确访问 myCarmakemodel 属性。