new操作符通过四步使this指向新实例:创建空对象、设置原型链、以该对象为this调用构造函数、默认返回该对象;构造函数内可直接用this添加属性方法,箭头函数继承外层this仍指向实例。

在 JavaScript 中,构造函数被 new 调用时,this 会自动绑定到新创建的空对象实例上——这是 new 操作符的内置行为,无需手动绑定。
new 操作符如何让 this 指向新实例
当你写 new Person("Alice"),JavaScript 引擎内部会执行四步:
- 创建一个全新的空对象(即实例)
- 将该对象的
[[Prototype]]指向构造函数的prototype - 以这个新对象为
this,调用构造函数(此时this已绑定) - 若构造函数没有显式返回对象,则默认返回该新对象
构造函数内 this 就是实例本身
你可以在构造函数中直接给 this 添加属性或方法,它们都会挂载到新实例上:
function Person(name) {<br> this.name = name; // this → 新实例<br> this.sayHi = function() {<br> return "Hi, I'm " + this.name;<br> };<br>}<br>const p = new Person("Bob");<br>console.log(p.name); // "Bob"<br>console.log(p.sayHi()); // "Hi, I'm Bob"
立即学习“Java免费学习笔记(深入)”;
注意:箭头函数在构造函数中不改变 this 绑定
箭头函数没有自己的 this,它会沿作用域链向上找外层普通函数的 this。如果在构造函数里定义箭头函数,它的 this 仍指向实例(因为外层是构造函数,其 this 是实例):
function Person(name) {<br> this.name = name;<br> this.sayHi = () => "Hi, I'm " + this.name; // this 正确指向实例<br>}
但要注意:这种方式定义的方法无法被原型共享,每次实例化都会新建函数,不如挂到 Person.prototype 上高效。
手动绑定 this 的情况通常不需要
除非你绕过 new 直接调用构造函数(比如 Person("Alice")),这时 this 会是全局对象(非严格模式)或 undefined(严格模式),导致意外行为。所以务必用 new;若想防御误调用,可在构造函数开头加检查:
function Person(name) {<br> if (!(this instanceof Person)) {<br> throw new Error("Person must be called with new");<br> }<br> this.name = name;<br>}


















