JS: Test existance of private element

By Xah Lee. Date: .

Test private element existance (#x in obj)

(new in ECMAScript 2022)

Syntax

#name in xobj

Allows you to test for existance of private element on objects.

This syntax can only be used inside class body.

Return true only if the private element #name exist in the object xobj where the check occur.

🛑 warning: if an object AA tests for #x, on a class BB that also has #x, result is false, because the #x is not in the same class of the test code.

Purpose (brand check)

It seems, the only purpose is for creating a method to test if the object is the class where the method is defined.

it's called “brand check”.

its similar to the purpose of “instanceof” operator except that “instanceof” is not guaranteed to be correct.

Example

class AA {
 // private field
 #xpriv;

 // check private field existance
 static isAA(xobj) {
  return #xpriv in xobj;
 }
}

console.assert(AA.isAA(new AA()) === true);

// s------------------------------
// test if it works on private field of the same name but in different object

class BB {
 #xpriv;
}

console.assert(AA.isAA(new BB()) === false);

Checking property existance (key in obj)

note, this is the same in operator fo checking property key, but with different purpose.