Parse-sdk-js: Parse.Query doesn't return instances of ES6 classes

Created on 9 Nov 2015  路  5Comments  路  Source: parse-community/Parse-SDK-JS

class Child extends Parse.Object {
  constructor() {
    super("Child");
  }
}
new Parse.Query(Child).find().then((children) = {
  if (children.length > 0) {
    console.log(children[0] instanceof Child); // prints "false"
  }
});

Works when Child is specified with old Parse.Object.extend syntax

question

Most helpful comment

When using es6 classes to extend Parse.Object you must register the subclass: Parse.Object.registerSubclass("className", constructor)

Just have a registration follow the class declaration:

class Child extends Parse.Object {
  constructor(attributes, options) {
    super("Child", attributes, options);
  }
}
Parse.Object.registerSubclass('Child', Child);

All 5 comments

what your showing is problematic. because Parse.Query cannot magically access this class that you created by this syntax. also if you'll have two declaration of the same class Child extends Parse.Object {路路路} JavaScript won't treat instance of one of them of the other. it's part of the way JavaScript works.
As everything else in JavaScript, it would advice to use duck typing checking:

children && children[0] && children[0].className === 'Child'

When using es6 classes to extend Parse.Object you must register the subclass: Parse.Object.registerSubclass("className", constructor)

Just have a registration follow the class declaration:

class Child extends Parse.Object {
  constructor(attributes, options) {
    super("Child", attributes, options);
  }
}
Parse.Object.registerSubclass('Child', Child);

Hi @myuller, we maintain an inner classMap to keep track of all subclasses of ParseObjct. When objects of a subclass are retrieved from a query, if we can find the subclass in the classMap, the objects will be instantiated with this subclass. In order to use the subclass in es6, you have to manually call registerSubclass. For es5, we have done that for you in extend, check here.
Thanks for your awesome explanation @TylerBrock.

@TylerBrock @wangmengyan95 Thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guilhermevini picture guilhermevini  路  6Comments

ryanemax picture ryanemax  路  7Comments

adrianchifor picture adrianchifor  路  3Comments

RaschidJFR picture RaschidJFR  路  7Comments

Simone-cogno picture Simone-cogno  路  7Comments