Why I cant use "this" to assign a object variable from a object to another variable in that object in JavaScript
why this work:
variable = "hi";
variabletwo = this. variable;
alert( variabletwo );
and this dont:
Object = {
variable: "hi",
variabletwo: this.variable
}
alert( Object.var开发者_运维技巧iabletwo );
in JavaScript.
Within a function body this
is a reference to the object on which the function was invoked. It is a very dynamic value - set at the point when the function is called.
Outside of a function this
doesn't make much sense - it will point to the global context.
In the original code this.variable will resolve to window.variable. e.g:
window.variable = 'global';
Object = {
variable: "hi",
variabletwo: this.variable
};
alert( Object.variabletwo );
// displays 'global'
However, within a function that is an object property (a method) this
will point to the object as you expected. e.g:
myObject = {
variable: "hi",
setTwo: function () {
this.variabletwo = this.variable;
}
};
myObject.setTwo();// when called `this` will point to myObject
alert(myObject.variabletwo);
// displays 'hi'
It's also worth noting that in your original you destroyed the reference to the native Object constructor. After executing your code you would find new Object()
would throw an error. i.e:
alert(Object === {}.constructor);
// displays false
Because you can't access the new object until after the initialiser expression.
The this
you have is the this that is outside the literal.
A simple test of this would be:
var self = this;
var anObject = { isThis: self === this }
alert(anObject.isThis)
In the first example, both vars are in the global scope, as is the reference to 'this'. In that scope, 'this' is the global, of which each var is a property. So 'variable' and 'this.variable', in the global scope, are the same thing.
In the second, however, 'this' is not referencing the same scope in which 'variable' lives. 'variable' lives under 'Object', so you would have to reference it as 'Object.variable'.
精彩评论