MST

星途 面试题库

面试题:JavaScript对象创建表达式之构造函数方式

请使用构造函数的方式创建一个名为`Person`的对象,该对象有`name`和`age`属性,以及一个`sayHello`方法,该方法能在控制台打印出`Hello, my name is [name] and I'm [age] years old`。然后创建一个`Person`的实例并调用`sayHello`方法。
35.3万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old`);
    };
}

const personInstance = new Person('John', 30);
personInstance.sayHello();