Javascript: 'this' changes when assigning a property?
I know 'this' can be a problem when you don't understand Javascript well but this one got me a little puzzled.
var ControlTypes = {
TextBox: function () {
console.log(this);
this.Name = "TextBox";
console.log(this);
}
}
ControlTypes.TextBox();
Firebug gives the following result:
Object {}
Object { Name="TextBox"}
The first object is ControlTy开发者_C百科pes and the second one is Textbox. Could anybody explain the behavior behind this?
var ControlTypes = {
TextBox: function () {
console.log(this);
this.Name = "TextBox";
console.log(this);
}
}
ControlTypes.TextBox();
You define a variable ControlTypes by a JavaScript Object Literal.
A member function is defined of named TextBox.
You have an object, with a member function. When that member function uses the "this" keyword, it is pointing to the container of the member function, your object "ControlTypes".
When you console.log this for the first time, no member variable where typeof(variable) != "function"
has been defined...
Then, you define a member variable "Name", so the next time you call console.log, Name has been defined.
By the way,
Are you attempting to instantiate a ControlTypes.TextBox object?
Currently you are running the TextBox function in the context of ControlTypes, not in a new object.
I think you meant new ControlTypes.TextBox();
The output of console.log
is different between the calls because you change it between the calls. Simple as that.
精彩评论