JavaScript中构造函数被new调用时,this自动绑定到新创建的空对象实例上;箭头函数无prototype且不支持new,故不能作构造函数;class是语法糖,其constructor中this绑定逻辑与普通构造函数一致。

在 JavaScript 中,构造函数被 new 调用时,this 会自动绑定到新创建的空对象实例上——这是语言内置机制,不需要手动干预。
构造函数调用时 this 的绑定规则
当使用 new 操作符调用函数时,JavaScript 引擎会按以下顺序执行:
- 创建一个全新的空对象(继承自该函数的
prototype) - 将这个新对象赋值给函数内部的
this - 执行函数体中的代码(此时所有对
this的属性赋值,都发生在新对象上) - 若函数没有显式返回对象,则默认返回这个新对象
为什么箭头函数不能用作构造函数
箭头函数没有自己的 this,它会沿作用域链向上捕获外层的 this 值;更重要的是,它没有 prototype 属性,也不支持 new 调用。尝试 new () => {} 会直接抛出 TypeError。
普通函数作为构造函数的典型写法
下面是一个标准示例:
立即学习“Java免费学习笔记(深入)”;
function Person(name) {
this.name = name; // this 指向 new 出来的实例
this.sayHello = function() {
console.log('Hello, ' + this.name);
};
}
const alice = new Person('Alice');
console.log(alice.name); // 'Alice'
console.log(alice.sayHello()); // 'Hello, Alice'
注意:每次实例化都会创建新的 sayHello 函数。若想复用方法,应把方法定义在 Person.prototype 上,这样所有实例共享同一函数,且其中的 this 依然指向各自调用者。
ES6 class 的本质仍是函数构造器
class 是语法糖,其 constructor 内部的 this 绑定逻辑与传统构造函数完全一致:
class Animal {
constructor(species) {
this.species = species; // this 就是 new 出来的实例
}
speak() {
return `I'm a ${this.species}`;
}
}
const dog = new Animal('dog');
console.log(dog.speak()); // 'I'm a dog'
class 构造器同样禁止用 new 调用箭头函数或普通函数表达式作为 constructor;且 class 内部方法默认不可枚举,但 this 行为不变。


















