JavaScript对象构造函数:为何用this而非直接使用对象名?
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:
- It creates a brand new, empty JavaScript object.
- It links this empty object to the constructor’s prototype (
y.prototype). - It calls the constructor function
y, and binds that new empty object as the value ofthisinside the constructor. - 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
xdoesn’t point to the new object until after the constructor runs, so referencing it inside the constructor is useless (it’s stillundefinedat that point).thisis the constructor’s way of referring to the new object thatnewcreated specifically for this instance—so usingthisensures you’re modifying the right object.
内容的提问来源于stack exchange,提问作者user2860957

