You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象构造函数:为何用this而非直接使用对象名?

Why this Works but Direct Object Name Doesn't in Constructor Functions

Great question! Let’s break this down clearly so you understand exactly what’s happening here.

First, let’s recap what new does when you call a constructor

When you run var x = new y('hello'), the new keyword handles a few critical steps behind the scenes:

  1. It creates a brand new, empty JavaScript object.
  2. It links this empty object to the constructor’s prototype (y.prototype).
  3. It calls the constructor function y, and binds that new empty object as the value of this inside the constructor.
  4. Unless the constructor explicitly returns another object, it automatically returns this new object, which then gets assigned to your variable x.

Why referencing x directly fails

Here’s the key mistake: When the constructor y runs, x hasn’t actually been assigned to the new object yet!

Yes, var x gets hoisted (declared at the top of the scope), but the assignment x = [result of new y()] only happens after the constructor finishes executing. So inside the constructor, x is still undefined. If you tried to run x.mes = mes, you’d be trying to set a property on undefined—which either throws an error or does absolutely nothing useful.

Why this works perfectly

As we covered earlier, when you call a function with new, this is bound to that fresh, empty object the new keyword created. So when you write this.mes = mes, you’re directly adding the mes property to that new object. Once the constructor finishes, this object is returned and assigned to x, which is why x.mes ends up with the value 'hello'.

Let’s test this with a quick modification to your code to see the difference:

var x = new y('hello');
function y(mes) {
  console.log('Inside constructor, x is:', x); // Logs "undefined"
  console.log('Inside constructor, this is:', this); // Logs the new empty object
  this.mes = mes;
}
console.log('After constructor, x.mes is:', x.mes); // Logs "hello"

To sum it up

  • x doesn’t point to the new object until after the constructor runs, so referencing it inside the constructor is useless (it’s still undefined at that point).
  • this is the constructor’s way of referring to the new object that new created specifically for this instance—so using this ensures you’re modifying the right object.

内容的提问来源于stack exchange,提问作者user2860957

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:14:38