MST

星途 面试题库

面试题:JavaScript 中类和构造函数安全设计的基本理解

在 JavaScript 中,简述使用构造函数创建对象时,可能出现的安全问题,并说明如何通过类的语法来更安全地创建对象。
38.8万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

使用构造函数创建对象可能出现的安全问题:

  1. this 指向错误:如果在调用构造函数时没有使用 new 关键字,this 可能会指向全局对象(在浏览器环境中是 window),而不是新创建的对象实例,这可能导致意外地在全局作用域中添加属性,污染全局命名空间。例如:
function Person(name) {
    this.name = name;
}
// 错误调用,没有使用 new
var person = Person('John'); 
// 这里 this 指向全局对象(window),会意外在全局添加 name 属性
console.log(window.name); 
  1. 属性覆盖风险:在构造函数内部,如果属性名不小心重复,可能会导致属性覆盖。例如:
function Animal(name) {
    this.name = name;
    this.type = 'mammal';
    // 假设这里误写了同样的属性名
    this.name = 'default'; 
}
var animal = new Animal('Lion');
console.log(animal.name); // 'default',原设置的 'Lion' 被覆盖

通过类的语法更安全地创建对象:

  1. 明确的构造函数调用:在 ES6 类语法中,构造函数必须使用 new 关键字调用,如果不使用 new,会抛出一个错误。例如:
class Person {
    constructor(name) {
        this.name = name;
    }
}
// 不使用 new 调用会报错
// var person = Person('John'); 
var person = new Person('John'); 
  1. 作用域清晰:类的语法提供了一个更清晰的作用域,属性和方法都在类的作用域内定义,减少了意外污染全局命名空间的可能性。例如:
class Animal {
    constructor(name, type) {
        this.name = name;
        this.type = type;
    }
}
var animal = new Animal('Lion', 'mammal');
// 不会污染全局命名空间
  1. 属性管理更清晰:在类中属性定义更加明确,有助于避免属性名重复导致的覆盖问题。例如:
class Plant {
    constructor(name, species) {
        this.name = name;
        this.species = species;
    }
}
var plant = new Plant('Rose', 'flowering plant');
// 清晰的属性定义,不易出现覆盖