面试题答案
一键面试性能差异原因
- 构造函数:每次通过构造函数创建新对象时,都会重新创建一份构造函数中定义的属性和方法。这意味着如果创建大量对象,会占用较多内存,因为每个对象都有重复的方法副本。例如:
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log('Hello, ' + this.name);
};
}
let person1 = new Person('Alice');
let person2 = new Person('Bob');
这里 person1
和 person2
都有自己独立的 sayHello
方法副本。
- 原型方法:原型方法定义在构造函数的
prototype
对象上,所有通过该构造函数创建的对象共享这些原型方法。这样可以节省内存,因为无论创建多少个对象,原型方法只有一份。例如:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
let person1 = new Person('Alice');
let person2 = new Person('Bob');
person1
和 person2
共享 Person.prototype.sayHello
方法。
性能表现更优的场景
- 构造函数性能更优的场景:当对象的方法需要访问构造函数的局部变量,并且这些方法不能共享时,使用构造函数定义方法更合适。例如,一个包含私有变量的计数器:
function Counter() {
let count = 0;
this.increment = function() {
count++;
console.log(count);
};
}
let counter1 = new Counter();
let counter2 = new Counter();
counter1.increment(); // 输出 1
counter2.increment(); // 输出 1
这里每个 Counter
实例都有自己独立的 count
变量和 increment
方法,适合使用构造函数定义。
- 原型方法性能更优的场景:当方法不需要访问构造函数的局部变量,并且可以被所有实例共享时,使用原型方法更优。例如,对象的通用功能,如上面的
sayHello
方法,所有Person
实例都可以共享这个方法,使用原型方法定义能节省内存。