I wasn’t sure how to ask this, and I apologize if it’s been asked already, but I could not find it or an answer.
What is returned when you assign a function to a var.
var obj = function(){
this.name = 'Steve';
}
alert( obj.name === '');//true
obj.name = 'Mike';
alert( obj.name === '');//true
obj.foo = 'fall';
alert( obj.foo );//fall
I know obj is now a function/object and I can call obj(). I also know that the function attached to obj is a constructor for new objects of type obj. If I do
var newObj = new obj();
alert( newObj.name );//Steve
“Steve” is printed. etc. etc.
Why does obj seem to have a property called “name” attached to it? And why when I try to assign a value to that property does it not get assigned?
Because function objects have a
nameproperty (which is non-standard by the way) that represents the “name” of the function, your function shows an empty string ("") as the value of this property because it’s anonymous.For example, if you declare a function with the name
foo:Also as you noted, you can’t change the value of this property, since in most implementations, it’s non-configurable, non-enumerable and non-writable:
Remember, this property is non-standard and there are some implementations that don’t support it (e.g. all IE JScript versions do not support it)
Now as @Felix suggest, I would like to add that
this.namedoesn’t have anything to do with your function’snameproperty.In your example, calling the
objfunction as a constructor (with thenewoperator), sets thethisvalue to a newly created object, that inherits from your function’s prototype, and you are assigning a value to thenameproperty to this new object.