简体   繁体   中英

what is the meaning of “if (this [x])” in Javascript

I'm using a javascript game engine called panda, and i'm getting an error in the console (Uncaught Class BG already created). And when i explore the source code of the engine, i found the code that is throwing the error (below). My question is, in the second if statement what is the meaning of (this[name])? i don't understand what exactly its saying. Any help would be appreciated. Thanks in advanced.

createClass: function(name, extend, content) {
    if (typeof name === 'object') return this.Class.extend(name);

    if (this[name]) throw 'Class ' + name + ' already created';

    if (typeof extend === 'object') {
        content = extend;
        extend = 'Class';
    }

There are two type of notation in JavaScript to refer object properties.

var Employee = { "firstname" : "John", "lastname" : "Smith" }

1. Dot notation

Employee.firstname; // John
Employee.lastname; // Smith

2. Bracket notation

var fname = "firstname";
var lname = "lastname";

Employee[fname]; // John
Employee[lname]; // Smith

So, incase if the object property is a variable we can user bracket notation.

So in your case this[name] is referring to a property on this object.

This is not really clear from the fragment of code, you've posted, but this might be some kind of class container.

if(this[name]) ... Checks for existence of property with the given name (which in this context shows if the class with such name is already registered.)

The fact you are getting the error means that you have tried to register two classes with the same name.

this[X] will check inside if condition value is undefined

if (this[name]) throw 'Class ' + name + ' already created';

if this[name] is undefined will not goes into if statement.

Example

var chkCondition;

alert(chkCondition);

// This will not goes inside if because chkCondition is undefined.
if (chkCondition) {
  alert('yes');
}

chkCondition="A";

// Now chkCondition has value "A" that's why it will return 
// true and goes inside if and alert "yes"
if (chkCondition) {
  alert('yes');
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM