Reputation: 61
I have a working piece of code until I added a last property to it. I know the issues of this in javascript. But this is something I have never encounter before.
var name = "John Dane";
var age = 24;
var person = {
id: 'emp133y1998',
name, age,
forEach: function(action) {
for (var prop in this) {
if(prop === 'forEach') continue;
action(this[prop]);
}
},
this: name +" "+ age
};
person.forEach(e => say(e));
If this
is keyword how can we use it as a property name. Even stranger thing is I can actually access it person.this
like this. But unfortunately my forEach
method broke after this. So I removed it. I'm still in learning phase. Can anyone explain what is actually happening here?
Upvotes: 1
Views: 89
Reputation: 73928
this
is a reserved keywords as of ECMAScript 2015 specification.
The language allow you to declare a property name with a reserved keywords using bracket syntax or not as mention by @squint.
Notes: Naked use of reserved words is supported from ES5 onwards not before.
Example valid for browser enviroment:
// this code works on before ES5 and onward
// this bracket syntax for maximum portability of your code
var obj = {};
obj['this'] = 'hello i am this'; // bracket syntax
obj['for'] = 'hello i am for';
alert(obj['this']);
alert(obj['for']);
// this code works on ES5 and onward
var obj = {};
obj.this = 'hello i am this'; // bracket syntax
obj.for = 'hello i am for';
alert(obj.this);
alert(obj.for);
IMO: I suggest to DO NOT use this
or other reserved keywords as a name of a property as could create subtitle bugs and could be confusing to human and build tools.
Upvotes: 2